laravel速记

Input::old(‘username‘)

Querying using raw SQL statements

$sql=" insert into shows(name,rating,actor) VALUES(?,?,?)";
        $data1 = array(‘Doctor Who‘, ‘9‘, ‘Matt Smith‘);
        $data2 = array(‘Arrested Development‘, ‘10‘, ‘Jason
        Bateman‘);
        $data3 = array(‘Joanie Loves Chachi‘, ‘3‘, ‘Scott
        Baio‘);
        DB::insert($sql,$data1);
        DB::insert($sql,$data2);
        DB::insert($sql,$data3);

$sql = "DELETE FROM shows WHERE name = ?";
        DB::delete($sql, array(‘Doctor Who‘));
        DB::delete($sql, array(‘Arrested Development‘));
        DB::delete($sql, array(‘Joanie Loves Chachi‘));
class Show {
public function allShows($order_by = FALSE,
$direction = ‘ASC‘)
{
$sql = ‘SELECT * FROM shows‘;
$sql .= $order_by ? ‘ ORDER BY ‘ . $order_by
. ‘ ‘ . $direction : ‘‘;
return DB::select($sql);
}
}
 Route::get("shows",function(){
     $shows=new Show();
     $shows_by_rating=$shows->allShows(‘rating‘,‘DESC‘);
     dd($shows_by_rating);
 });
 

dd:Dump the passed variables and end the script.

    $data1 = array(‘name‘ => ‘Doctor Who‘,
            ‘rating‘ => 9, ‘actor‘ => ‘Matt Smith‘);
            $data2 = array(‘name‘ => ‘Arrested Development‘,
            ‘rating‘ => 10, ‘actor‘ => ‘Jason Bateman‘);
            $data3 = array(‘name‘ => ‘Joanie Loves Chachi‘,
            ‘rating‘ => 3, ‘actor‘ => ‘Scott Baio‘);
        DB::table(‘shows‘)->insert(array($data1,$data2,$data3));

DB::table(‘shows‘)->where(‘name‘, ‘Doctor Who‘)
        ->orWhere(‘name‘, ‘Arrested Development‘)
        ->orWhere(‘name‘, ‘Joanie Loves Chachi‘)
        ->delete();

获取model所有数据。

$shows=Show::all();
echo ‘<h1>All shows</h1>‘;
foreach($shows as $show)
{
echo $show->name,‘ - ‘.$show->rating . ‘ - ‘. $show->actor .‘<br/>‘;

}

用户验证:

<?php
class User extends Eloquent {
protected $table = ‘users‘;
private $rules = array(
‘email‘ => ‘required|email‘,
‘username‘ => ‘required|min:6‘
);
public function validate($input) {
return Validator::make($input, $this->rules);
}
}

Make a route that loads the ORM and tries to save some data:
$user = new User();
$input = array();
$input[‘email‘] = ‘[email protected]‘;
$input[‘username‘] = ‘Short‘;
$valid = $user->validate($input);
if ($valid->passes()) {
echo ‘Everything is Valid!‘;
// Save to the database
} else {
var_dump($valid->messages());
}

There are a few other ways to validate our data using models. One way is to use a package
that will handle most of the validation work for us. One great package to use is Ardent, which
can be found at https://github.com/laravelbook/ardent.

Using advanced Eloquent and relationships

Schema::create(‘show_user‘, function($table)
{
$table->increments(‘id‘);
$table->integer(‘user_id‘);
$table->integer(‘show_id‘);
$table->timestamps();
});

Create a User.php file in the app/model directory:
class User extends Eloquent {
public function shows()
{
return $this->belongsToMany (‘Show‘);
}
}
5. Create a Show.php file in our app/model directory:
class Show extends Eloquent {
public function users()
{
return $this->belongsToMany (‘User‘);
}
}
6. Make a route in routes.php to add a new user and attach two shows:

Route::get(‘add-show‘, function()
{
    $user=new User();
    $user->username = ‘John Doe‘;
    $user->email = ‘[email protected]‘;
    $user->save();

    //attach two shows
    $user->shows()->attach(1);
    $user->shows()->attach(3);
    foreach($user->shows()->get() as $show)
    {
        var_dump($show->name);

    }
});

Make a route to get all the users attached to a show:
Route::get(‘view-show‘, function()
{
$show = Show::find(1)->users;
dd($show);
});

There‘s more...
Database relationships can get fairly complicated and this recipe merely scratches the surface
of what can be done. To learn more about how Laravel‘s Eloquent ORM uses relationships, view
the documentation at http://laravel.com/docs/eloquent#many-to-many.

该文档部分内容:

Many-to-many relations are a more complicated relationship type. An example of such a relationship is a user with many roles, where the roles are also shared by other users. For example, many users may have the role of "Admin". Three database tables are needed for this relationship: users,roles, and role_user. The role_user table is derived from the alphabetical order of the related model names, and should have user_id and role_id columns.

We can define a many-to-many relation using the belongsToMany method:

class User extends Eloquent {

    public function roles()
    {
        return $this->belongsToMany(‘Role‘);
    }

}

Now, we can retrieve the roles through the User model:

$roles = User::find(1)->roles;

If you would like to use an unconventional table name for your pivot table, you may pass it as the second argument to the belongsToMany method:

return $this->belongsToMany(‘Role‘, ‘user_roles‘);

You may also override the conventional associated keys:

return $this->belongsToMany(‘Role‘, ‘user_roles‘, ‘user_id‘, ‘foo_id‘);

Of course, you may also define the inverse of the relationship on the Role model:

class Role extends Eloquent {

    public function users()
    {
        return $this->belongsToMany(‘User‘);
    }

}

Creating a CRUD system
To interact with our database, we might need to create a CRUD (create, read, update, and
delete) system. That way, we add and alter our data without needing a separate database
client. This recipe will be using a RESTful controller for our CRUD system.

<?php
class  UsersController extends BaseController {
    public function getIndex()
    {
        $users=User::all();
        return View::make(‘users.index‘)->with(‘users‘,$users);
    }
    public function getCreate()
    {
        return View::make("users.create");
    }
    public function postCreate()
    {
        $user=new User();
        $user->username=Input::get("username");
        $user->email=Input::get("email");

        $user->save();
        return Redirect::to(‘users‘);

    }
    //编辑Edit get
    public function getRecord($id)
    {
        $user=User::find($id);
        return View::make(‘users.record‘)->with(‘user‘,$user);
    }
    //编辑Edit post
    public function putRecord()
    {
    $user = User::find(Input::get(‘user_id‘));
    $user->username = Input::get(‘username‘);
    $user->email = Input::get(‘email‘);
    $user->save();
    return Redirect::to(‘users‘);
    }
    public function deleteRecord()
    {
    $user = User::find(Input::get(‘user_id‘))
    ->delete();
    return Redirect::to(‘users‘);
    }
}

路由:Route::controller(‘users‘, ‘UsersController‘);

仅仅看上面的或许不理解,看官网文档:

RESTful Controllers

Laravel allows you to easily define a single route to handle every action in a controller using simple, REST naming conventions. First, define the route using the Route::controller method:

Route::controller(‘users‘, ‘UserController‘);

The controller method accepts two arguments. The first is the base URI the controller handles, while the second is the class name of the controller. Next, just add methods to your controller, prefixed with the HTTP verb they respond to:

class UserController extends BaseController {

    public function getIndex()
    {
        //
    }

    public function postProfile()
    {
        //
    }

    public function anyLogin()
    {
        //
    }

}

The index methods will respond to the root URI handled by the controller, which, in this case, isusers.

If your controller action contains multiple words, you may access the action using "dash" syntax in the URI. For example, the following controller action on our UserController would respond to the users/admin-profile URI:

public function getAdminProfile() {}

官网文档看完了,接着上面的。几个视图如下:index.php
<style>
table, th, td {
border:1px solid #444
}
</style>
<table>
<thead>
<tr>
<th>User ID</th>
<th>User Name</th>
<th>Email</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
<?php foreach($users as $user): ?>
<tr>
<td><?php echo $user->id ?></td>
<td><?php echo $user->username ?></td>
<td><?php echo $user->email ?></td>
<td>
<a href="users/record/<?php echo $user->id ?>">Edit</a>

<form action="users/record" method="post">
    <input type="hidden" name="_method" value="DELETE">
   <input type="hidden" name="user_id"  value="<?php echo $user->id ?>">
<input type="submit" value="Delete">
</form>

</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
<a href="users/create">Add New User</a>

注意画红线的:

<input type="hidden" name="_method" value="DELETE">.如果去掉这个点击delete会找不到,原因大概是因为http现在不支持delete和put方法,laravel采用了一个隐藏的_method 来实现这个。create.php
<form action="create" method="post">
Username:<br>
<input name="username"><br>
Email<br>
<input name="email"><br>
<input type="submit">
</form>

record.php

<form action="" method="post">
<input type="hidden" name="_method" value="put">
<input type="hidden" name="user_id" value="<?php echo $user->id ?>">
  Username:<br>
<input name="username" value="<?php echo $user->username ?>"><br>
Email<br>
<input name="email" value="<?php echo $user->email ?>"><br>
<input type="submit">
</form>
------------------------一个小技巧

Using attributes to change table column name

Sometimes we may be working with a database that was created using less-than-logical
column names. In those cases, we can use Laravel‘s Eloquent ORM to allows us to interact
with the table using more standardized names, without having to make database changes.

比如user表有个column name是MyUsernameGoesHere,

这个非常不好,可以在模型里面定义一个方法:

public function getUsernameAttribute($value) {
return $this->attributes[‘MyUsernameGoesHere‘];
}

然后就可以用$odd->username 了。

Building a RESTful API with routes

A common need for a modern web application is having an API that third-parties can run
queries against. Since Laravel is built with RESTful patterns as a focus, it‘s quite easy to build
a full API with very little work.

参考<laravel devolpment cookbook>

We could also use Laravel‘s resourceful controllers to accomplish something similar. More
information about those can be found in the documentation at http://laravel.com/
docs/controllers#resource-controllers.

传递数据给view

Route::get(‘home‘, function()
{
$page_title = ‘My Home Page Title‘;
return View::make(‘myviews.home‘)->with(‘title‘,
$page_title);
});

Route::get(‘second‘, function()
{
$view = View::make(‘myviews.second‘);
$view->my_name = ‘John Doe‘;
$view->my_city = ‘Austin‘;
return $view;
});

There‘s more...
One other way to add data to our views is similar to the way in our second route; however we
use an array instead of an object. So our code would look similar to the following:
$view = View::make(‘myviews.second‘);
$view[‘my_name‘] = ‘John Doe‘;
$view[‘my_city‘] = ‘Austin‘;
return $view;

Loading a view into another view/nested views

Route::get(‘home‘, function()
{
return View::make(‘myviews.home‘)
->nest(‘header‘, ‘common.header‘)
->nest(‘footer‘, ‘common.footer‘);
});

home.php:

<?= $header ?>
<h1>Welcome to the Home page!</h1>
<p>
<a href="second">Go to Second Page</a>
</p>
<?= $footer ?>

adding assets增加资产

Adding assets
A dynamic website almost requires the use of CSS and JavaScript. Using a Laravel asset
package provides an easy way to manage these assets and include them in our views.

时间: 2025-01-02 04:11:16

laravel速记的相关文章

Laravel 5.4 中的异常处理器和HTTP异常处理实例教程

错误和异常是处理程序开发中不可回避的议题,在本地开发中我们往往希望能捕获程序抛出的异常并将其显示打印出来,以便直观的知道程序在哪里出了问题并予以解决,而在线上环境我们不希望将程序错误或异常显示在浏览器中(出于安全考虑),这个时候我们仍然要捕获异常,只不过不是显示到浏览器中,而是记录到日志中,方便日后排查问题. 百牛信息技术bainiu.ltd整理发布于博客园 Laravel当然支持PHP原生的错误和异常处理,但是在此基础上进行了一些封装处理,从而更方便在不同开发环境切换以及对错误和异常的处理.

laravel框架数据迁移

迁移就像数据库的版本控制,允许团队简单轻松的编辑并共享应用的数据库表结构,迁移通常和Laravel 的 schema 构建器结对从而可以很容易地构建应用的数据库表结构.如果你曾经告知小组成员需要手动添加列到本地数据库结构,那么这正是数据库迁移所致力于解决的问题. Laravel 的 Schema 门面提供了与数据库系统无关的创建和操纵表的支持,在 Laravel 所支持的所有数据库系统中提供一致的.优雅的.平滑的 API. laravel默认有两个文件uses  和 password_reset

详细说明php的4中开源框架(TP,CI,Laravel,Yii)

ThinkPHP简称TP,TP借鉴了Java思想,基于PHP5,充分利用了PHP5的特性,部署简单只需要一个入口文件,一起搞定,简单高效.中文文档齐全,入门超级简单.自带模板引擎,具有独特的数据验证和自动填充功能,框架更新速度比较速度. 优点:这个框架易使用 易学 安全 对bae sae支持很好提供的工具也很强大 可以支持比较大的项目开发 易扩展 全中文文档 总的来说这款框架适合非常适合国人使用 性能 上比CI还要强一些 缺点:配置对有些人来说有些复杂(其实是因为没有认真的读过其框架源码)文档有

Laravel 5.0 - Middleware (中间件)

图片:http://stackphp.com/ 如上图所示,中心的绿色区域是整个应用的核心区域. 所以,中间件就是一系列处理请求和响应的方式而不是你用程序逻辑的一部分. Laravel 中默认使用中间件处理请求中的加密解密,以及 Cookies 和 Sessions.你也可以自定义自己所需的中间件. 写中间件 artisan make:middleware MyMiddleware 执行上面的命令,生成中间件文件: <?php namespace App\Http\Middleware; use

laravel安装笔记

一.安装composer 安装之前将\php\php.ini文件中的php_openssl.dll扩展库开启,否则composer在安装过程中会出现错误提示. (我在安装过程中发现apache目录下的php.ini最好也开启php_openssl.dll,就是讲前面的‘:’号去掉) composer下载地址:https://getcomposer.org/ windows下载地址:https://getcomposer.org/Composer-Setup.exe 二.下载Laravel最新框架

Laravel 5.5 的自定义验证对象/类

本文和大家分享的主要是Laravel 5.5 的自定义验证对象/类相关内容,一起来看看吧,希望对大家学习Laravel有所帮助. Laravel 5.5 将提供一个全新的自定义验证规则的对象,以作为原来的 Validator::extend 方法的替代. Laravel 中的表单验证是比较方便的,而且内置了大量的可用验证规则,但不管官方提供了多少,总还是会有满足不了需求的时候.很多时候我们会直接用正则表达式来处理这种特殊的验证,也有时候我们会选择用 Validator::extend来扩展一个自

laravel 数据库操作小例子

public function demo() { $res = null; //insert数据插入 //$user=array('username'=>'joy','password'=>'123456','age'=>23); //$res = DB::table('users')->insert($user); /* 数据查询 $res = DB::table('users')->where('username','joy')->get(); $res = DB:

微信公开课(北京站)速记 微信、微信支付、O2O的定义与关联

本文为4月29日微信公开课(北京站)微信产品部演讲全文速记,讲述了微信官方对微信.微信支付.O2O的定义与关联等问题的看法与观点. 作者:微信产品部 刘涵涛 吴毅 去年夏天有一个全民打飞机的盛况,这实际上是微信的第一款社交类手游,它通过微信大平台的海量用户,一上线之后就有过亿的用户,甚至在淘宝上面都有代客打游戏的服务,通过这个游戏大家突然想到,微信以前是一个沟通工具,微信竟然也可以玩儿,甚至出现了这样一个段子,如果要自己的排行榜排在前面,最简单的方法是把玩这个游戏的好朋友全部踢掉. 微信红包大家

Laravel中常见的错误与解决方法小结

一.报错: 「Can't swap PDO instance while within transaction」 通过查询 Laravel 源代码,可以确认异常是在 setPdo 方法中抛出的: ? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 <?php public function setPdo($pdo) {   if ($this->transactions >= 1) {     throw new RuntimeException("