Artisan

  1. // 在版本 5.1.11 新添加,见 http://d.laravel-china.org/docs/5.1/authorization#creating-policiesphp artisan make:policy PostPolicy
  2. // 针对命令显示帮助信息php artisan --help OR -h
  3. // 抑制输出信息php artisan --quiet OR -q
  4. // 打印 Laravel 的版本信息php artisan --version OR -V
  5. // 不询问任何交互性的问题php artisan --no-interaction OR -n
  6. // 强制输出 ANSI 格式php artisan --ansi
  7. // 禁止输出 ANSI 格式php artisan --no-ansi
  8. // 显示当前命令行运行的环境php artisan --env
  9. // -v|vv|vvv 通过增加 v 的个数来控制命令行输出内容的详尽情况: 1 个代表正常输出, 2 个代表输出更多消息, 3 个代表调试php artisan --verbose
  10. // 移除编译优化过的文件 (storage/frameworks/compiled.php)php artisan clear-compiled
  11. // 显示当前框架运行的环境php artisan env// 显示某个命令的帮助信息php artisan help// 显示所有可用的命令php artisan list// 进入应用交互模式php artisan tinker// 进入维护模式php artisan down// 退出维护模式php artisan up// 优化框架性能// --force 强制编译已写入文件 (storage/frameworks/compiled.php)// --psr 不对 Composer 的 dump-autoload 进行优化php artisan optimize [--force] [--psr]
  12. // 启动内置服务器php artisan serve// 更改默认端口php artisan serve --port 8080
  13. // 使其在本地服务器外也可正常工作php artisan serve --host 0.0.0.0
  14. // 更改应用命名空间php artisan app:name namespace
  15. // 清除过期的密码重置令牌php artisan auth:clear-resets
  16. // 清空应用缓存php artisan cache:clear
  17. // 创建缓存数据库表 migrationphp artisan cache:table
  18. // 合并所有的配置信息为一个,提高加载速度php artisan config:cache
  19. // 移除配置缓存文件php artisan config:clear
  20. // 程序内部调用 Artisan 命令$exitCode = Artisan::call('config:cache');
  21. // 运行所有的 seed 假数据生成类// --class 可以指定运行的类,默认是: "DatabaseSeeder"// --database 可以指定数据库// --force 当处于生产环境时强制执行操作php artisan db:seed [--class[="..."]] [--database[="..."]] [--force]
  22.  
  23. // 基于注册的信息,生成遗漏的 events 和 handlersphp artisan event:generate
  24.  
  25. // 生成新的处理器类// --command 需要处理器处理的命令类名字php artisan handler:command [--command="..."] name
  26. // 创建一个新的时间处理器类// --event 需要处理器处理的事件类名字// --queued 需要处理器使用队列话处理的事件类名字php artisan handler:event [--event="..."] [--queued] name
  27.  
  28. // 生成应用的 key(会覆盖)php artisan key:generate
  29.  
  30. // 在默认情况下, 这将创建未加入队列的自处理命令// 通过 --handler 标识来生成一个处理器, 用 --queued 来使其入队列.php artisan make:command [--handler] [--queued] name
  31. // 创建一个新的 Artisan 命令// --command 命令被调用的名称。 (默认为: "command:name")php artisan make:console [--command[="..."]] name
  32. // 创建一个新的资源控制器// --plain 生成一个空白的控制器类php artisan make:controller [--plain] name
  33. php artisan make:controller App\\Admin\\Http\\Controllers\\DashboardController
  34. // 创建一个新的事件类php artisan make:event name
  35. // 创建一个新的中间件类php artisan make:middleware name
  36. // 创建一个新的迁移文件// --create 将被创建的数据表.// --table 将被迁移的数据表.php artisan make:migration [--create[="..."]] [--table[="..."]] name
  37. // 创建一个新的 Eloquent 模型类php artisan make:model name
  38. // 创建一个新的服务提供者类php artisan make:provider name
  39. // 创建一个新的表单请求类php artisan make:request name
  40. // 数据库迁移// --database 指定数据库连接(下同)// --force 当处于生产环境时强制执行,不询问(下同)// --path 指定单独迁移文件地址// --pretend 把将要运行的 SQL 语句打印出来(下同)// --seed Seed 任务是否需要被重新运行(下同)php artisan migrate [--database[="..."]] [--force] [--path[="..."]] [--pretend] [--seed]
  41. // 创建迁移数据库表php artisan migrate:install [--database[="..."]]
  42. // 重置并重新运行所有的 migrations// --seeder 指定主 Seeder 的类名php artisan migrate:refresh [--database[="..."]] [--force] [--seed] [--seeder[="..."]]
  43. // 回滚所有的数据库迁移php artisan migrate:reset [--database[="..."]] [--force] [--pretend]
  44. // 回滚最最近一次运行的迁移任务php artisan migrate:rollback [--database[="..."]] [--force] [--pretend]
  45. // migrations 数据库表信息php artisan migrate:status
  46. // 为队列数据库表创建一个新的迁移php artisan queue:table
  47. // 监听指定的队列// --queue 被监听的队列// --delay 给执行失败的任务设置延时时间 (默认为零: 0)// --memory 内存限制大小,单位为 MB (默认为: 128)// --timeout 指定任务运行超时秒数 (默认为: 60)// --sleep 等待检查队列任务的秒数 (默认为: 3)// --tries 任务记录失败重试次数 (默认为: 0)php artisan queue:listen [--queue[="..."]] [--delay[="..."]] [--memory[="..."]] [--timeout[="..."]] [--sleep[="..."]] [--tries[="..."]] [connection]
  48. // 查看所有执行失败的队列任务php artisan queue:failed
  49. // 为执行失败的数据表任务创建一个迁移php artisan queue:failed-table
  50. // 清除所有执行失败的队列任务php artisan queue:flush
  51. // 删除一个执行失败的队列任务php artisan queue:forget
  52. // 在当前的队列任务执行完毕后, 重启队列的守护进程php artisan queue:restart
  53. // 对指定 id 的执行失败的队列任务进行重试(id: 失败队列任务的 ID)php artisan queue:retry id
  54. // 指定订阅 Iron.io 队列的链接// queue: Iron.io 的队列名称.// url: 将被订阅的 URL.// --type 指定队列的推送类型.php artisan queue:subscribe [--type[="..."]] queue url
  55. // 处理下一个队列任务// --queue 被监听的队列// --daemon 在后台模式运行// --delay 给执行失败的任务设置延时时间 (默认为零: 0)// --force 强制在「维护模式下」运行// --memory 内存限制大小,单位为 MB (默认为: 128)// --sleep 当没有任务处于有效状态时, 设置其进入休眠的秒数 (默认为: 3)// --tries 任务记录失败重试次数 (默认为: 0)php artisan queue:work [--queue[="..."]] [--daemon] [--delay[="..."]] [--force] [--memory[="..."]] [--sleep[="..."]] [--tries[="..."]] [connection]
  56.  
  57. // 生成路由缓存文件来提升路由效率php artisan route:cache
  58. // 移除路由缓存文件php artisan route:clear
  59. // 显示已注册过的路由php artisan route:list
  60.  
  61. // 运行计划命令php artisan schedule:run
  62.  
  63. // 为 session 数据表生成迁移文件php artisan session:table
  64.  
  65. // 从 vendor 的扩展包中发布任何可发布的资源// --force 重写所有已存在的文件// --provider 指定你想要发布资源文件的服务提供者// --tag 指定你想要发布标记资源.php artisan vendor:publish [--force] [--provider[="..."]] [--tag[="..."]]
  66. php artisan tail [--path[="..."]] [--lines[="..."]] [connection]

Composer

  1. composer create-project laravel/laravel folder_name
  2. composer install
  3. composer update
  4. composer dump-autoload [--optimize]
  5. composer self-update
  6. composer require [options] [--] [vendor/packages]...

Config

  1. Config::get('app.timezone');
  2. //指定默认值Config::get('app.timezone', 'UTC');
  3. Config::set('database.default', 'sqlite');

Route

  1. Route::get('foo', function(){});
  2. Route::get('foo', 'ControllerName@function');
  3. Route::controller('foo', 'FooController');
资源路由
  1. Route::resource('posts','PostsController');
  2. // 资源路由器只允许指定动作通过Route::resource('photo', 'PhotoController',['only' => ['index', 'show']]);
  3. Route::resource('photo', 'PhotoController',['except' => ['update', 'destroy']]);
触发错误
  1. App::abort(404);
  2. $handler->missing(...) in ErrorServiceProvider::boot();
  3. throw new NotFoundHttpException;
路由参数
  1. Route::get('foo/{bar}', function($bar){});
  2. Route::get('foo/{bar?}', function($bar = 'bar'){});
HTTP 请求方式
  1. Route::any('foo', function(){});
  2. Route::post('foo', function(){});
  3. Route::put('foo', function(){});
  4. Route::patch('foo', function(){});
  5. Route::delete('foo', function(){});
  6. // RESTful 资源控制器Route::resource('foo', 'FooController');
  7. // 为一个路由注册多种请求方式Route::match(['get', 'post'], '/', function(){});
安全路由 (TBD)
  1. Route::get('foo', array('https', function(){}));
路由约束
  1. Route::get('foo/{bar}', function($bar){})
  2. ->where('bar', '[0-9]+');
  3. Route::get('foo/{bar}/{baz}', function($bar, $baz){})
  4. ->where(array('bar' => '[0-9]+', 'baz' => '[A-Za-z]'))
  1. // 设置一个可跨路由使用的模式Route::pattern('bar', '[0-9]+')
HTTP 中间件
  1. // 为路由指定 MiddlewareRoute::get('admin/profile', ['middleware' => 'auth', function(){}]);
  2. Route::get('admin/profile', function(){})->middleware('auth');
命名路由
  1. Route::currentRouteName();
  2. Route::get('foo/bar', array('as' => 'foobar', function(){}));
  3. Route::get('user/profile', [
  4. 'as' => 'profile', 'uses' => 'UserController@showProfile'
  5. ]);
  6. Route::get('user/profile', 'UserController@showProfile')->name('profile');
  7. $url = route('profile');
  8. $redirect = redirect()->route('profile');
路由前缀
  1. Route::group(['prefix' => 'admin'], function()
  2. {
  3. Route::get('users', function(){
  4. return 'Matches The "/admin/users" URL';
  5. });
  6. });
路由命名空间
  1. // 此路由组将会传送 'Foo\Bar' 命名空间Route::group(array('namespace' => 'Foo\Bar'), function(){})
子域名路由
  1. // {sub} 将在闭包中被忽略Route::group(array('domain' => '{sub}.example.com'), function(){});

Environment

  1. $environment = app()->environment();
  2. $environment = App::environment();
  3. $environment = $app->environment();
  4. // 判断当环境是否为 localif ($app->environment('local')){}
  5. // 判断当环境是否为 local 或 staging...if ($app->environment('local', 'staging')){}

Log

  1. // 记录器提供了 7 种在 RFC 5424 标准内定义的记录等级:// debug, info, notice, warning, error, critical, and alert.Log::info('info');
  2. Log::info('info',array('context'=>'additional info'));
  3. Log::error('error');
  4. Log::warning('warning');
  5. // 获取 monolog 实例Log::getMonolog();
  6. // 添加监听器Log::listen(function($level, $message, $context) {});
记录 SQL 查询语句
  1. // 开启 logDB::connection()->enableQueryLog();
  2. // 获取已执行的查询数组DB::getQueryLog();

URL

  1. URL::full();
  2. URL::current();
  3. URL::previous();
  4. URL::to('foo/bar', $parameters, $secure);
  5. URL::action('NewsController@item', ['id'=>123]);
  6. // 需要在适当的命名空间内URL::action('Auth\AuthController@logout');
  7. URL::action('FooController@method', $parameters, $absolute);
  8. URL::route('foo', $parameters, $absolute);
  9. URL::secure('foo/bar', $parameters);
  10. URL::asset('css/foo.css', $secure);
  11. URL::secureAsset('css/foo.css');
  12. URL::isValidUrl('http://example.com');
  13. URL::getRequest();
  14. URL::setRequest($request);

Event

  1. Event::fire('foo.bar', array($bar));
  2. // 注册一个事件监听器.// void listen(string|array $events, mixed $listener, int $priority)Event::listen('App\Events\UserSignup', function($bar){});
  3. Event::listen('foo.*', function($bar){});
  4. Event::listen('foo.bar', 'FooHandler', 10);
  5. Event::listen('foo.bar', 'BarHandler', 5);
  6. // 你可以直接在处理逻辑中返回 false 来停止一个事件的传播.Event::listen('foor.bar', function($event){ return false; });
  7. Event::subscribe('UserEventHandler');

DB

基本使用
  1. DB::connection('connection_name');
  2. // 运行数据库查询语句$results = DB::select('select * from users where id = ?', [1]);
  3. $results = DB::select('select * from users where id = :id', ['id' => 1]);
  4. // 运行普通语句DB::statement('drop table users');
  5. // 监听查询事件DB::listen(function($sql, $bindings, $time){ code_here; });
  6. // 数据库事务处理DB::transaction(function()
  7. {
  8. DB::table('users')->update(['votes' => 1]);
  9. DB::table('posts')->delete();
  10. });
  11. DB::beginTransaction();
  12. DB::rollBack();
  13. DB::commit();
查询语句构造器
  1. // 取得数据表的所有行DB::table('name')->get();
  2. // 取数据表的部分数据DB::table('users')->chunk(100, function($users)
  3. {
  4. foreach ($users as $user)
  5. {
  6. //}
  7. });
  8. // 取回数据表的第一条数据$user = DB::table('users')->where('name', 'John')->first();
  9. DB::table('name')->first();
  10. // 从单行中取出单列数据$name = DB::table('users')->where('name', 'John')->pluck('name');
  11. DB::table('name')->pluck('column');
  12. // 取多行数据的「列数据」数组$roles = DB::table('roles')->lists('title');
  13. $roles = DB::table('roles')->lists('title', 'name');
  14. // 指定一个选择字句$users = DB::table('users')->select('name', 'email')->get();
  15. $users = DB::table('users')->distinct()->get();
  16. $users = DB::table('users')->select('name as user_name')->get();
  17. // 添加一个选择字句到一个已存在的查询语句中$query = DB::table('users')->select('name');
  18. $users = $query->addSelect('age')->get();
  19. // 使用 Where 运算符$users = DB::table('users')->where('votes', '>', 100)->get();
  20. $users = DB::table('users')
  21. ->where('votes', '>', 100)
  22. ->orWhere('name', 'John')
  23. ->get();
  24. $users = DB::table('users')
  25. ->whereBetween('votes', [1, 100])->get();
  26. $users = DB::table('users')
  27. ->whereNotBetween('votes', [1, 100])->get();
  28. $users = DB::table('users')
  29. ->whereIn('id', [1, 2, 3])->get();
  30. $users = DB::table('users')
  31. ->whereNotIn('id', [1, 2, 3])->get();
  32. $users = DB::table('users')
  33. ->whereNull('updated_at')->get();
  34. DB::table('name')->whereNotNull('column')->get();
  35. // 动态的 Where 字句$admin = DB::table('users')->whereId(1)->first();
  36. $john = DB::table('users')
  37. ->whereIdAndEmail(2, 'john@doe.com')
  38. ->first();
  39. $jane = DB::table('users')
  40. ->whereNameOrAge('Jane', 22)
  41. ->first();
  42. // Order By, Group By, 和 Having$users = DB::table('users')
  43. ->orderBy('name', 'desc')
  44. ->groupBy('count')
  45. ->having('count', '>', 100)
  46. ->get();
  47. DB::table('name')->orderBy('column')->get();
  48. DB::table('name')->orderBy('column','desc')->get();
  49. DB::table('name')->having('count', '>', 100)->get();
  50. // 偏移 & 限制$users = DB::table('users')->skip(10)->take(5)->get();
Joins
  1. // 基本的 Join 声明语句DB::table('users')
  2. ->join('contacts', 'users.id', '=', 'contacts.user_id')
  3. ->join('orders', 'users.id', '=', 'orders.user_id')
  4. ->select('users.id', 'contacts.phone', 'orders.price')
  5. ->get();
  6. // Left Join 声明语句DB::table('users')
  7. ->leftJoin('posts', 'users.id', '=', 'posts.user_id')
  8. ->get();
  9. // select * from users where name = 'John' or (votes > 100 and title <> 'Admin')DB::table('users')
  10. ->where('name', '=', 'John')
  11. ->orWhere(function($query)
  12. {
  13. $query->where('votes', '>', 100)
  14. ->where('title', '<>', 'Admin');
  15. })
  16. ->get();
聚合
  1. $users = DB::table('users')->count();
  2. $price = DB::table('orders')->max('price');
  3. $price = DB::table('orders')->min('price');
  4. $price = DB::table('orders')->avg('price');
  5. $total = DB::table('users')->sum('votes');
原始表达句
  1. $users = DB::table('users')
  2. ->select(DB::raw('count(*) as user_count, status'))
  3. ->where('status', '<>', 1)
  4. ->groupBy('status')
  5. ->get();
  6. // 返回行DB::select('select * from users where id = ?', array('value'));
  7. DB::insert('insert into foo set bar=2');
  8. DB::update('update foo set bar=2');
  9. DB::delete('delete from bar');
  10. // 返回 voidDB::statement('update foo set bar=2');
  11. // 在声明语句中加入原始的表达式DB::table('name')->select(DB::raw('count(*) as count, column2'))->get();
Inserts / Updates / Deletes / Unions / Pessimistic Locking
  1. // 插入DB::table('users')->insert(
  2. ['email' => 'john@example.com', 'votes' => 0]
  3. );
  4. $id = DB::table('users')->insertGetId(
  5. ['email' => 'john@example.com', 'votes' => 0]
  6. );
  7. DB::table('users')->insert([
  8. ['email' => 'taylor@example.com', 'votes' => 0],
  9. ['email' => 'dayle@example.com', 'votes' => 0]
  10. ]);
  11. // 更新DB::table('users')
  12. ->where('id', 1)
  13. ->update(['votes' => 1]);
  14. DB::table('users')->increment('votes');
  15. DB::table('users')->increment('votes', 5);
  16. DB::table('users')->decrement('votes');
  17. DB::table('users')->decrement('votes', 5);
  18. DB::table('users')->increment('votes', 1, ['name' => 'John']);
  19. // 删除DB::table('users')->where('votes', '<', 100)->delete();
  20. DB::table('users')->delete();
  21. DB::table('users')->truncate();
  22. // 集合// unionAll() 方法也是可供使用的,调用方式与 union 相似$first = DB::table('users')->whereNull('first_name');
  23. $users = DB::table('users')->whereNull('last_name')->union($first)->get();
  24. // 消极锁DB::table('users')->where('votes', '>', 100)->sharedLock()->get();
  25. DB::table('users')->where('votes', '>', 100)->lockForUpdate()->get();

Model

基础使用
  1. // 定义一个 Eloquent 模型class User extends Model {}
  2. // 生成一个 Eloquent 模型php artisan make:model User
  3. // 指定一个自定义的数据表名称class User extends Model {
  4. protected $table = 'my_users';
  5. }
More
  1. Model::create(array('key' => 'value'));
  2. // 通过属性找到第一条相匹配的数据或创造一条新数据Model::firstOrCreate(array('key' => 'value'));
  3. // 通过属性找到第一条相匹配的数据或实例化一条新数据Model::firstOrNew(array('key' => 'value'));
  4. // 通过属性找到相匹配的数据并更新,如果不存在即创建Model::updateOrCreate(array('search_key' => 'search_value'), array('key' => 'value'));
  5. // 使用属性的数组来填充一个模型, 用的时候要小心「Mass Assignment」安全问题 !Model::fill($attributes);
  6. Model::destroy(1);
  7. Model::all();
  8. Model::find(1);
  9. // 使用双主键进行查找Model::find(array('first', 'last'));
  10. // 查找失败时抛出异常Model::findOrFail(1);
  11. // 使用双主键进行查找, 失败时抛出异常Model::findOrFail(array('first', 'last'));
  12. Model::where('foo', '=', 'bar')->get();
  13. Model::where('foo', '=', 'bar')->first();
  14. Model::where('foo', '=', 'bar')->exists();
  15. // 动态属性查找Model::whereFoo('bar')->first();
  16. // 查找失败时抛出异常Model::where('foo', '=', 'bar')->firstOrFail();
  17. Model::where('foo', '=', 'bar')->count();
  18. Model::where('foo', '=', 'bar')->delete();
  19. // 输出原始的查询语句Model::where('foo', '=', 'bar')->toSql();
  20. Model::whereRaw('foo = bar and cars = 2', array(20))->get();
  21. Model::on('connection-name')->find(1);
  22. Model::with('relation')->get();
  23. Model::all()->take(10);
  24. Model::all()->skip(10);
  25. // 默认的 Eloquent 排序是上升排序Model::all()->orderBy('column');
  26. Model::all()->orderBy('column','desc');
软删除
  1. Model::withTrashed()->where('cars', 2)->get();
  2. // 在查询结果中包括带被软删除的模型Model::withTrashed()->where('cars', 2)->restore();
  3. Model::where('cars', 2)->forceDelete();
  4. // 查找只带有软删除的模型Model::onlyTrashed()->where('cars', 2)->get();
模型关联
  1. // 一对一 - User::phone()return $this->hasOne('App\Phone', 'foreign_key', 'local_key');
  2. // 一对一 - Phone::user(), 定义相对的关联return $this->belongsTo('App\User', 'foreign_key', 'other_key');
  3.  
  4. // 一对多 - Post::comments()return $this->hasMany('App\Comment', 'foreign_key', 'local_key');
  5. // 一对多 - Comment::post()return $this->belongsTo('App\Post', 'foreign_key', 'other_key');
  6.  
  7. // 多对多 - User::roles();return $this->belongsToMany('App\Role', 'user_roles', 'user_id', 'role_id');
  8. // 多对多 - Role::users();return $this->belongsToMany('App\User');
  9. // 多对多 - Retrieving Intermediate Table Columns$role->pivot->created_at;
  10. // 多对多 - 中介表字段return $this->belongsToMany('App\Role')->withPivot('column1', 'column2');
  11. // 多对多 - 自动维护 created_at 和 updated_at 时间戳return $this->belongsToMany('App\Role')->withTimestamps();
  12.  
  13. // 远层一对多 - Country::posts(), 一个 Country 模型可能通过中介的 Users// 模型关联到多个 Posts 模型(User::country_id)return $this->hasManyThrough('App\Post', 'App\User', 'country_id', 'user_id');
  14.  
  15. // 多态关联 - Photo::imageable()return $this->morphTo();
  16. // 多态关联 - Staff::photos()return $this->morphMany('App\Photo', 'imageable');
  17. // 多态关联 - Product::photos()return $this->morphMany('App\Photo', 'imageable');
  18. // 多态关联 - 在 AppServiceProvider 中注册你的「多态对照表」Relation::morphMap([
  19. 'Post' => App\Post::class,
  20. 'Comment' => App\Comment::class,
  21. ]);
  22.  
  23. // 多态多对多关联 - 涉及数据库表: posts,videos,tags,taggables// Post::tags()return $this->morphToMany('App\Tag', 'taggable');
  24. // Video::tags()return $this->morphToMany('App\Tag', 'taggable');
  25. // Tag::posts()return $this->morphedByMany('App\Post', 'taggable');
  26. // Tag::videos()return $this->morphedByMany('App\Video', 'taggable');
  27.  
  28. // 查找关联$user->posts()->where('active', 1)->get();
  29. // 获取所有至少有一篇评论的文章...$posts = App\Post::has('comments')->get();
  30. // 获取所有至少有三篇评论的文章...$posts = Post::has('comments', '>=', 3)->get();
  31. // 获取所有至少有一篇评论被评分的文章...$posts = Post::has('comments.votes')->get();
  32. // 获取所有至少有一篇评论相似于 foo% 的文章$posts = Post::whereHas('comments', function ($query) {
  33. $query->where('content', 'like', 'foo%');
  34. })->get();
  35.  
  36. // 预加载$books = App\Book::with('author')->get();
  37. $books = App\Book::with('author', 'publisher')->get();
  38. $books = App\Book::with('author.contacts')->get();
  39.  
  40. // 延迟预加载$books->load('author', 'publisher');
  41.  
  42. // 写入关联模型$comment = new App\Comment(['message' => 'A new comment.']);
  43. $post->comments()->save($comment);
  44. // Save 与多对多关联$post->comments()->saveMany([
  45. new App\Comment(['message' => 'A new comment.']),
  46. new App\Comment(['message' => 'Another comment.']),
  47. ]);
  48. $post->comments()->create(['message' => 'A new comment.']);
  49.  
  50. // 更新「从属」关联$user->account()->associate($account);
  51. $user->save();
  52. $user->account()->dissociate();
  53. $user->save();
  54.  
  55. // 附加多对多关系$user->roles()->attach($roleId);
  56. $user->roles()->attach($roleId, ['expires' => $expires]);
  57. // 从用户上移除单一身份...$user->roles()->detach($roleId);
  58. // 从用户上移除所有身份...$user->roles()->detach();
  59. $user->roles()->detach([1, 2, 3]);
  60. $user->roles()->attach([1 => ['expires' => $expires], 2, 3]);
  61.  
  62. // 任何不在给定数组中的 IDs 将会从中介表中被删除。$user->roles()->sync([1, 2, 3]);
  63. // 你也可以传递中介表上该 IDs 额外的值:$user->roles()->sync([1 => ['expires' => true], 2, 3]);
  64.  
  65. 事件
  66. Model::creating(function($model){});
  67. Model::created(function($model){});
  68. Model::updating(function($model){});
  69. Model::updated(function($model){});
  70. Model::saving(function($model){});
  71. Model::saved(function($model){});
  72. Model::deleting(function($model){});
  73. Model::deleted(function($model){});
  74. Model::observe(new FooObserver);
  75.  
  76. Eloquent 配置信息
  77. // 关闭模型插入或更新操作引发的 「mass assignment」异常Eloquent::unguard();
  78. // 重新开启「mass assignment」异常抛出功能Eloquent::reguard();

Pagination

  1. // 自动处理分页逻辑Model::paginate(15);
  2. Model::where('cars', 2)->paginate(15);
  3. // 使用简单模板 - 只有 "上一页" 或 "下一页" 链接Model::where('cars', 2)->simplePaginate(15);
  4. // 手动分页Paginator::make($items, $totalItems, $perPage);
  5. // 在页面打印分页导航栏$variable->links();

Lang

  1. App::setLocale('en');
  2. Lang::get('messages.welcome');
  3. Lang::get('messages.welcome', array('foo' => 'Bar'));
  4. Lang::has('messages.welcome');
  5. Lang::choice('messages.apples', 10);
  6. // Lang::get 的别名trans('messages.welcome');

File

  1. File::exists('path');
  2. File::get('path');
  3. File::getRemote('path');
  4. // 获取文件内容File::getRequire('path');
  5. // 获取文件内容, 仅能引入一次File::requireOnce('path');
  6. // 将内容写入文件File::put('path', 'contents');
  7. // 将内容添加在文件原内容后File::append('path', 'data');
  8. // 通过给定的路径来删除文件File::delete('path');
  9. // 将文件移动到新目录下File::move('path', 'target');
  10. // Copy a file to a new location// 将文件复制到新目录下File::copy('path', 'target');
  11. // 从文件的路径地址提取文件的扩展File::extension('path');
  12. // 获取文件类型File::type('path');
  13. // 获取文件大小File::size('path');
  14. // 获取文件的最后修改时间File::lastModified('path');
  15. // 判断给定的路径是否是文件目录File::isDirectory('directory');
  16. // 判断给定的路径是否是可写入的File::isWritable('path');
  17. // 判断给定的路径是否是文件File::isFile('file');
  18. // 查找能被匹配到的路径名File::glob($patterns, $flag);
  19. // Get an array of all files in a directory.// 获取一个目录下的所有文件, 以数组类型返回File::files('directory');
  20. // 获取一个目录下的所有文件 (递归).File::allFiles('directory');
  21. // 获取一个目录内的目录File::directories('directory');
  22. // 创建一个目录File::makeDirectory('path', $mode = 0777, $recursive = false);
  23. // 将文件夹从一个目录复制到另一个目录下File::copyDirectory('directory', 'destination', $options = null);
  24. // 递归式删除目录File::deleteDirectory('directory', $preserve = false);
  25. // 清空指定目录的所有文件和文件夹File::cleanDirectory('directory');

UnitTest

Install and run
  1. // 将其加入到 composer.json 并更新:composer require "phpunit/phpunit:4.0.*"
  2. // 运行测试 (在项目根目录下运行)./vendor/bin/phpunit
Asserts
  1. $this->assertTrue(true);
  2. $this->assertEquals('foo', $bar);
  3. $this->assertCount(1,$times);
  4. $this->assertResponseOk();
  5. $this->assertResponseStatus(403);
  6. $this->assertRedirectedTo('foo');
  7. $this->assertRedirectedToRoute('route.name');
  8. $this->assertRedirectedToAction('Controller@method');
  9. $this->assertViewHas('name');
  10. $this->assertViewHas('age', $value);
  11. $this->assertSessionHasErrors();
  12. // 由单个 key 值来假定 session 有错误...$this->assertSessionHasErrors('name');
  13. // 由多个 key 值来假定 session 有错误...$this->assertSessionHasErrors(array('name', 'age'));
  14. $this->assertHasOldInput();
Calling routes
  1. $response = $this->call($method, $uri, $parameters, $files, $server, $content);
  2. $response = $this->callSecure('GET', 'foo/bar');
  3. $this->session(['foo' => 'bar']);
  4. $this->flushSession();
  5. $this->seed();
  6. $this->seed($connection);

SSH

Executing Commands
  1. SSH::run(array $commands);
  2. // 指定 remote, 否则将使用默认值SSH::into($remote)->run(array $commands);
  3. SSH::run(array $commands, function($line)
  4. {
  5. echo $line.PHP_EOL;
  6. });
任务
  1. // 定义任务SSH::define($taskName, array $commands);
  2. // 执行任务SSH::task($taskName, function($line)
  3. {
  4. echo $line.PHP_EOL;
  5. });
SFTP 上传
  1. SSH::put($localFile, $remotePath);
  2. SSH::putString($string, $remotePath);

Schema

  1. // 创建指定数据表Schema::create('table', function($table)
  2. {
  3. $table->increments('id');
  4. });
  5. // 指定一个连接Schema::connection('foo')->create('table', function($table){});
  6. // 通过给定的名称来重命名数据表Schema::rename($from, $to);
  7. // 移除指定数据表Schema::drop('table');
  8. // 当数据表存在时, 将指定数据表移除Schema::dropIfExists('table');
  9. // 判断数据表是否存在Schema::hasTable('table');
  10. // 判断数据表是否有该列Schema::hasColumn('table', 'column');
  11. // 更新一个已存在的数据表Schema::table('table', function($table){});
  12. // 重命名数据表的列$table->renameColumn('from', 'to');
  13. // 移除指定的数据表列$table->dropColumn(string|array);
  14. // 指定数据表使用的存储引擎$table->engine = 'InnoDB';
  15. // 字段顺序,只能在 MySQL 中才能用$table->string('name')->after('email');
索引
  1. $table->string('column')->unique();
  2. $table->primary('column');
  3. // 创建一个双主键$table->primary(array('first', 'last'));
  4. $table->unique('column');
  5. $table->unique('column', 'key_name');
  6. // 创建一个双唯一性索引$table->unique(array('first', 'last'));
  7. $table->unique(array('first', 'last'), 'key_name');
  8. $table->index('column');
  9. $table->index('column', 'key_name');
  10. // 创建一个双索引$table->index(array('first', 'last'));
  11. $table->index(array('first', 'last'), 'key_name');
  12. $table->dropPrimary(array('column'));
  13. $table->dropPrimary('table_column_primary');
  14. $table->dropUnique(array('column'));
  15. $table->dropUnique('table_column_unique');
  16. $table->dropIndex(array('column'));
  17. $table->dropIndex('table_column_index');
外键
  1. $table->foreign('user_id')->references('id')->on('users');
  2. $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade'|'restrict'|'set null'|'no action');
  3. $table->foreign('user_id')->references('id')->on('users')->onUpdate('cascade'|'restrict'|'set null'|'no action');
  4. $table->dropForeign(array('user_id'));
  5. $table->dropForeign('posts_user_id_foreign');
字段类型
  1. // 自增$table->increments('id');
  2. $table->bigIncrements('id');
  3.  
  4. // 数字$table->integer('votes');
  5. $table->tinyInteger('votes');
  6. $table->smallInteger('votes');
  7. $table->mediumInteger('votes');
  8. $table->bigInteger('votes');
  9. $table->float('amount');
  10. $table->double('column', 15, 8);
  11. $table->decimal('amount', 5, 2);
  12.  
  13. // 字符串和文本$table->char('name', 4);
  14. $table->string('email');
  15. $table->string('name', 100);
  16. $table->text('description');
  17. $table->mediumText('description');
  18. $table->longText('description');
  19.  
  20. // 日期和时间$table->date('created_at');
  21. $table->dateTime('created_at');
  22. $table->time('sunrise');
  23. $table->timestamp('added_on');
  24. // Adds created_at and updated_at columns// 添加 created_at 和 updated_at 行$table->timestamps();
  25. $table->nullableTimestamps();
  26.  
  27. // 其它类型$table->binary('data');
  28. $table->boolean('confirmed');
  29. // 为软删除添加 deleted_at 字段$table->softDeletes();
  30. $table->enum('choices', array('foo', 'bar'));
  31. // 添加 remember_token 为 VARCHAR(100) NULL$table->rememberToken();
  32. // 添加整型的 parent_id 和字符串类型的 parent_type$table->morphs('parent');
  33. ->nullable()
  34. ->default($value)
  35. ->unsigned()

Input

  1. Input::get('key');
  2. // 指定默认值Input::get('key', 'default');
  3. Input::has('key');
  4. Input::all();
  5. // 只取回 'foo' 和 'bar',返回数组Input::only('foo', 'bar');
  6. // 取除了 'foo' 的所有用户输入数组Input::except('foo');
  7. Input::flush();
会话周期内 Input
  1. // 清除会话周期内的输入Input::flash();
  2. // 清除会话周期内的指定输入Input::flashOnly('foo', 'bar');
  3. // 清除会话周期内的除了指定的其他输入Input::flashExcept('foo', 'baz');
  4. // 取回一个旧的输入条目Input::old('key','default_value');
Files
  1. // 使用一个已上传的文件Input::file('filename');
  2. // 判断文件是否已上传Input::hasFile('filename');
  3. // 获取文件属性Input::file('name')->getRealPath();
  4. Input::file('name')->getClientOriginalName();
  5. Input::file('name')->getClientOriginalExtension();
  6. Input::file('name')->getSize();
  7. Input::file('name')->getMimeType();
  8. // 移动一个已上传的文件Input::file('name')->move($destinationPath);
  9. // 移动一个已上传的文件,并设置新的名字Input::file('name')->move($destinationPath, $fileName);

Cache

  1. Cache::put('key', 'value', $minutes);
  2. Cache::add('key', 'value', $minutes);
  3. Cache::forever('key', 'value');
  4. Cache::remember('key', $minutes, function(){ return 'value' });
  5. Cache::rememberForever('key', function(){ return 'value' });
  6. Cache::forget('key');
  7. Cache::has('key');
  8. Cache::get('key');
  9. Cache::get('key', 'default');
  10. Cache::get('key', function(){ return 'default'; });
  11. Cache::tags('my-tag')->put('key','value', $minutes);
  12. Cache::tags('my-tag')->has('key');
  13. Cache::tags('my-tag')->get('key');
  14. Cache::tags('my-tag')->forget('key');
  15. Cache::tags('my-tag')->flush();
  16. Cache::increment('key');
  17. Cache::increment('key', $amount);
  18. Cache::decrement('key');
  19. Cache::decrement('key', $amount);
  20. Cache::section('group')->put('key', $value);
  21. Cache::section('group')->get('key');
  22. Cache::section('group')->flush();

Cookie

  1. Cookie::get('key');
  2. Cookie::get('key', 'default');
  3. // 创建一个永久有效的 cookieCookie::forever('key', 'value');
  4. // 创建一个 N 分钟有效的 cookieCookie::make('key', 'value', 'minutes');
  5. // 在回应之前先积累 cookie,回应时统一返回Cookie::queue('key', 'value', 'minutes');
  6. // 移除 CookieCookie::forget('key');
  7. // 从 response 发送一个 cookie$response = Response::make('Hello World');
  8. $response->withCookie(Cookie::make('name', 'value', $minutes));

Session

  1. Session::get('key');
  2. // 从会话中读取一个条目Session::get('key', 'default');
  3. Session::get('key', function(){ return 'default'; });
  4. // 获取 session 的 IDSession::getId();
  5. // 增加一个会话键值数据Session::put('key', 'value');
  6. // 将一个值加入到 session 的数组中Session::push('foo.bar','value');
  7. // 返回 session 的所有条目Session::all();
  8. // 检查 session 里是否有此条目Session::has('key');
  9. // 从 session 中移除一个条目Session::forget('key');
  10. // 从 session 中移除所有条目Session::flush();
  11. // 生成一个新的 session 标识符Session::regenerate();
  12. // 把一条数据暂存到 session 中Session::flash('key', 'value');
  13. // 清空所有的暂存数据Session::reflash();
  14. // 重新暂存当前暂存数据的子集Session::keep(array('key1', 'key2'));

Request

  1. // url: http://xx.com/aa/bbRequest::url();
  2. // 路径: /aa/bbRequest::path();
  3. // 获取请求 Uri: /aa/bb/?c=dRequest::getRequestUri();
  4. // 返回用户的 IPRequest::ip();
  5. // 获取 Uri: http://xx.com/aa/bb/?c=dRequest::getUri();
  6. // 获取查询字符串: c=dRequest::getQueryString();
  7. // 获取请求端口 (例如 80, 443 等等)Request::getPort();
  8. // 判断当前请求的 URI 是否可被匹配Request::is('foo/*');
  9. // 获取 URI 的分段值 (索引从 1 开始)Request::segment(1);
  10. // 从请求中取回头部信息Request::header('Content-Type');
  11. // 从请求中取回服务器变量Request::server('PATH_INFO');
  12. // 判断请求是否是 AJAX 请求Request::ajax();
  13. // 判断请求是否使用 HTTPSRequest::secure();
  14. // 获取请求方法Request::method();
  15. // 判断请求方法是否是指定类型的Request::isMethod('post');
  16. // 获取原始的 POST 数据Request::instance()->getContent();
  17. // 获取请求要求返回的格式Request::format();
  18. // 判断 HTTP Content-Type 头部信息是否包含 */jsonRequest::isJson();
  19. // 判断 HTTP Accept 头部信息是否为 application/jsonRequest::wantsJson();

Response

  1. return Response::make($contents);
  2. return Response::make($contents, 200);
  3. return Response::json(array('key' => 'value'));
  4. return Response::json(array('key' => 'value'))
  5. ->setCallback(Input::get('callback'));
  6. return Response::download($filepath);
  7. return Response::download($filepath, $filename, $headers);
  8. // 创建一个回应且修改其头部信息的值$response = Response::make($contents, 200);
  9. $response->header('Content-Type', 'application/json');
  10. return $response;
  11. // 为回应附加上 cookiereturn Response::make($content)
  12. ->withCookie(Cookie::make('key', 'value'));

Redirect

  1. return Redirect::to('foo/bar');
  2. return Redirect::to('foo/bar')->with('key', 'value');
  3. return Redirect::to('foo/bar')->withInput(Input::get());
  4. return Redirect::to('foo/bar')->withInput(Input::except('password'));
  5. return Redirect::to('foo/bar')->withErrors($validator);
  6. // 重定向到之前的请求return Redirect::back();
  7. // 重定向到命名路由(根据命名路由算出 URL)return Redirect::route('foobar');
  8. return Redirect::route('foobar', array('value'));
  9. return Redirect::route('foobar', array('key' => 'value'));
  10. // 重定向到控制器动作(根据控制器动作算出 URL)return Redirect::action('FooController@index');
  11. return Redirect::action('FooController@baz', array('value'));
  12. return Redirect::action('FooController@baz', array('key' => 'value'));
  13. // 跳转到目的地址,如果没有设置则使用默认值 foo/barreturn Redirect::intended('foo/bar');

Container

  1. App::bind('foo', function($app){ return new Foo; });
  2. App::make('foo');
  3. // 如果存在此类, 则返回App::make('FooBar');
  4. // 单例模式实例到服务容器中App::singleton('foo', function(){ return new Foo; });
  5. // 将已实例化的对象注册到服务容器中App::instance('foo', new Foo);
  6. // 注册绑定规则到服务容器中App::bind('FooRepositoryInterface', 'BarRepository');
  7. // 给应用注册一个服务提供者App::register('FooServiceProvider');
  8. // 监听容器对某个对象的解析App::resolving(function($object){});

Security

哈希
  1. Hash::make('secretpassword');
  2. Hash::check('secretpassword', $hashedPassword);
  3. Hash::needsRehash($hashedPassword);
加密解密
  1. Crypt::encrypt('secretstring');
  2. Crypt::decrypt($encryptedString);
  3. Crypt::setMode('ctr');
  4. Crypt::setCipher($cipher);

Auth

用户认证
  1. // 判断当前用户是否已认证(是否已登录)Auth::check();
  2. // 获取当前的认证用户Auth::user();
  3. // 获取当前的认证用户的 ID(未登录情况下会报错)Auth::id();
  4. // 通过给定的信息来尝试对用户进行认证(成功后会自动启动会话)Auth::attempt(['email' => $email, 'password' => $password]);
  5. // 通过 Auth::attempt() 传入 true 值来开启 '记住我' 功能Auth::attempt($credentials, true);
  6. // 只针对一次的请求来认证用户Auth::once($credentials);
  7. // 登录一个指定用户到应用上Auth::login(User::find(1));
  8. // 登录指定用户 ID 的用户到应用上Auth::loginUsingId(1);
  9. // 使用户退出登录(清除会话)Auth::logout();
  10. // 验证用户凭证Auth::validate($credentials);
  11. // Attempt to authenticate using HTTP Basic Auth// 使用 HTTP 的基本认证方式来认证Auth::basic('username');
  12. // Perform a stateless HTTP Basic login attempt// 执行「HTTP Basic」登录尝试Auth::onceBasic();
  13. // 发送密码重置提示给用户Password::remind($credentials, function($message, $user){});
用户授权
  1. // 定义权限Gate::define('update-post', 'Class@method');
  2. Gate::define('update-post', function ($user, $post) {...});
  3. // 传递多个参数Gate::define('delete-comment', function ($user, $post, $comment) {});
  4.  
  5. // 检查权限Gate::denies('update-post', $post);
  6. Gate::allows('update-post', $post);
  7. Gate::check('update-post', $post);
  8. // 指定用户进行检查Gate::forUser($user)->allows('update-post', $post);
  9. // 在 User 模型下,使用 Authorizable traitUser::find(1)->can('update-post', $post);
  10. User::find(1)->cannot('update-post', $post);
  11.  
  12. // 拦截所有检查Gate::before(function ($user, $ability) {});
  13. Gate::after(function ($user, $ability) {});
  14.  
  15. // Blade 模板语法@can('update-post', $post)
  16. @endcan
  17. // 支持 else 表达式@can('update-post', $post)
  18. @else
  19. @endcan
  20.  
  21. // 生成一个新的策略php artisan make:policy PostPolicy
  22. // `policy` 帮助函数policy($post)->update($user, $post)
  23.  
  24. // 控制器授权$this->authorize('update', $post);
  25. // 指定用户 $user 授权$this->authorizeForUser($user, 'update', $post);

Mail

  1. Mail::send('email.view', $data, function($message){});
  2. Mail::send(array('html.view', 'text.view'), $data, $callback);
  3. Mail::queue('email.view', $data, function($message){});
  4. Mail::queueOn('queue-name', 'email.view', $data, $callback);
  5. Mail::later(5, 'email.view', $data, function($message){});
  6. // 零时将发送邮件请求写入 log,方便测试Mail::pretend();
消息
  1. // 这些都能在 $message 实例中使用, 并可传入到 Mail::send() 或 Mail::queue()$message->from('email@example.com', 'Mr. Example');
  2. $message->sender('email@example.com', 'Mr. Example');
  3. $message->returnPath('email@example.com');
  4. $message->to('email@example.com', 'Mr. Example');
  5. $message->cc('email@example.com', 'Mr. Example');
  6. $message->bcc('email@example.com', 'Mr. Example');
  7. $message->replyTo('email@example.com', 'Mr. Example');
  8. $message->subject('Welcome to the Jungle');
  9. $message->priority(2);
  10. $message->attach('foo\bar.txt', $options);
  11. // 使用内存数据作为附件$message->attachData('bar', 'Data Name', $options);
  12. // 附带文件,并返回 CID$message->embed('foo\bar.txt');
  13. $message->embedData('foo', 'Data Name', $options);
  14. // 获取底层的 Swift Message 对象$message->getSwiftMessage();

Queue

  1. Queue::push('SendMail', array('message' => $message));
  2. Queue::push('SendEmail@send', array('message' => $message));
  3. Queue::push(function($job) use $id {});
  4. // 在多个 workers 中使用相同的负载Queue::bulk(array('SendEmail', 'NotifyUser'), $payload);
  5. // 开启队列监听器php artisan queue:listen
  6. php artisan queue:listen connection
  7. php artisan queue:listen --timeout=60
  8. // 只处理第一个队列任务php artisan queue:work
  9. // 在后台模式启动一个队列 workerphp artisan queue:work --daemon
  10. // 为失败的任务创建 migration 文件php artisan queue:failed-table
  11. // 监听失败任务php artisan queue:failed
  12. // 通过 id 删除失败的任务php artisan queue:forget 5
  13. // 删除所有失败任务php artisan queue:flush

Validation

  1. Validator::make(
  2. array('key' => 'Foo'),
  3. array('key' => 'required|in:Foo')
  4. );
  5. Validator::extend('foo', function($attribute, $value, $params){});
  6. Validator::extend('foo', 'FooValidator@validate');
  7. Validator::resolver(function($translator, $data, $rules, $msgs)
  8. {
  9. return new FooValidator($translator, $data, $rules, $msgs);
  10. });
Rules
  1. accepted
  2. active_url
  3. after:YYYY-MM-DD
  4. before:YYYY-MM-DD
  5. alpha
  6. alpha_dash
  7. alpha_num
  8. array
  9. between:1,10
  10. confirmed
  11. date
  12. date_format:YYYY-MM-DD
  13. different:fieldname
  14. digits:value
  15. digits_between:min,max
  16. boolean
  17. email
  18. exists:table,column
  19. image
  20. in:foo,bar,...
  21. not_in:foo,bar,...
  22. integer
  23. numeric
  24. ip
  25. max:value
  26. min:value
  27. mimes:jpeg,png
  28. regex:[0-9]
  29. required
  30. required_if:field,value
  31. required_with:foo,bar,...
  32. required_with_all:foo,bar,...
  33. required_without:foo,bar,...
  34. required_without_all:foo,bar,...
  35. same:field
  36. size:value
  37. timezone
  38. unique:table,column,except,idColumn
  39. url

View

  1. View::make('path/to/view');
  2. View::make('foo/bar')->with('key', 'value');
  3. View::make('foo/bar')->withKey('value');
  4. View::make('foo/bar', array('key' => 'value'));
  5. View::exists('foo/bar');
  6. // 跨视图共享变量View::share('key', 'value');
  7. // 视图嵌套View::make('foo/bar')->nest('name', 'foo/baz', $data);
  8. // 注册一个视图构造器View::composer('viewname', function($view){});
  9. // 注册多个视图到一个视图构造器中View::composer(array('view1', 'view2'), function($view){});
  10. // 注册一个视图构造器类View::composer('viewname', 'FooComposer');
  11. View::creator('viewname', function($view){});

Blade

  1. // 区块占位@yield('name')
  2. // 扩展布局模板@extends('layout.name')
  3. // 实现命名为 name 的区块(yield 占位的地方)@section('name')
  4. @stop
  5. // 可继承内容区块@section('sidebar')
  6. @show
  7. // 继承父模板内容(@show 的区块内容)@parent
  8. // 包含子视图@include('view.name')
  9. // 包含子视图,并传参@include('view.name', array('key' => 'value'));
  10. // 加载本地化语句@lang('messages.name')
  11. @choice('messages.name', 1);
  12.  
  13. @if
  14. @else
  15. @elseif
  16. @endif
  17.  
  18. @unless
  19. @endunless
  20.  
  21. @for
  22. @endfor
  23.  
  24. @foreach
  25. @endforeach
  26.  
  27. @while
  28. @endwhile
  29.  
  30. //forelse 4.2 feature@forelse($users as $user)
  31. @empty
  32. @endforelse
  33.  
  34. // 输出内容,被转义过的{{ $var }}
  35. // 输出未转义内容,5.0 特性{!! $var !!}
  36. {{-- Blade 注释,不会被输出到页面中 --}}
  37. // 三元表达式的简写,以下相当于「$name ? $name : 'Default'」{{{ $name or 'Default' }}}
  38. // 保留双大括号,以下会编译为 {{ name }}@{{ name }}

Form

  1. Form::open(array('url' => 'foo/bar', 'method' => 'PUT'));
  2. Form::open(array('route' => 'foo.bar'));
  3. Form::open(array('route' => array('foo.bar', $parameter)));
  4. Form::open(array('action' => 'FooController@method'));
  5. Form::open(array('action' => array('FooController@method', $parameter)));
  6. Form::open(array('url' => 'foo/bar', 'files' => true));
  7. Form::close();
  8. Form::token();
  9. Form::model($foo, array('route' => array('foo.bar', $foo->bar)));
Form Elements
  1. Form::label('id', 'Description');
  2. Form::label('id', 'Description', array('class' => 'foo'));
  3. Form::text('name');
  4. Form::text('name', $value);
  5. Form::text('name', $value, array('class' => 'name'));
  6. Form::textarea('name');
  7. Form::textarea('name', $value);
  8. Form::textarea('name', $value, array('class' => 'name'));
  9. Form::hidden('foo', $value);
  10. Form::password('password');
  11. Form::password('password', array('placeholder' => 'Password'));
  12. Form::email('name', $value, array());
  13. Form::file('name', array('class' => 'name'));
  14. Form::checkbox('name', 'value');
  15. // 生成一个被选中的复选框Form::checkbox('name', 'value', true, array('class' => 'name'));
  16. Form::radio('name', 'value');
  17. // 生成一个被选中的单选框Form::radio('name', 'value', true, array('class' => 'name'));
  18. Form::select('name', array('key' => 'value'));
  19. Form::select('name', array('key' => 'value'), 'key', array('class' => 'name'));
  20. Form::selectRange('range', 1, 10);
  21. Form::selectYear('year', 2011, 2015);
  22. Form::selectMonth('month');
  23. Form::submit('Submit!', array('class' => 'name'));
  24. Form::button('name', array('class' => 'name'));
  25. Form::macro('fooField', function()
  26. {
  27. return '<input type="custom"/>';
  28. });
  29. Form::fooField();

HTML

  1. HTML::macro('name', function(){});
  2. // 将 HTML 字符串转为实体HTML::entities($value);
  3. // 将实体转为 HTML 字符HTML::decode($value);
  4. // 生成 JavaScript 文件链接HTML::script($url, $attributes);
  5. // 生成 CSS 文件链接HTML::style($url, $attributes);
  6. // 生成一个 HTML 图片元素HTML::image($url, $alt, $attributes);
  7. // 生成一个 HTML 链接HTML::link($url, 'title', $attributes, $secure);
  8. // 生成一个 HTTPS 类型的 HTML 链接HTML::secureLink($url, 'title', $attributes);
  9. // 给资源文件生成一个 HTML linkHTML::linkAsset($url, 'title', $attributes, $secure);
  10. // 给资源文件生成一个 HTTPS HTML 链接HTML::linkSecureAsset($url, 'title', $attributes);
  11. // 给命名路由生成一个 HTML 链接HTML::linkRoute($name, 'title', $parameters, $attributes);
  12. // 给控制器动作生成 HTML 链接HTML::linkAction($action, 'title', $parameters, $attributes);
  13. // 给邮件地址生成 HTML 链接HTML::mailto($email, 'title', $attributes);
  14. // 混淆一个邮件地址以阻止垃圾邮件扫描器的嗅探HTML::email($email);
  15. // 生成有序列表HTML::ol($list, $attributes);
  16. // 生成无序列表HTML::ul($list, $attributes);
  17. HTML::listing($type, $list, $attributes);
  18. HTML::listingElement($key, $type, $value);
  19. HTML::nestedListing($key, $type, $value);
  20. // 从数组中构建 HTML 属性HTML::attributes($attributes);
  21. // 构建单属性元素HTML::attributeElement($key, $value);
  22. // 混淆一个字符串以阻止垃圾邮件扫描器的嗅探HTML::obfuscate($value);

String

  1. // 将 UTF-8 的值直译为 ASCII 类型的值Str::ascii($value)
  2. Str::camel($value)
  3. Str::contains($haystack, $needle)
  4. Str::endsWith($haystack, $needles)
  5. Str::finish($value, $cap)
  6. Str::is($pattern, $value)
  7. Str::length($value)
  8. Str::limit($value, $limit = 100, $end = '...')
  9. Str::lower($value)
  10. Str::words($value, $words = 100, $end = '...')
  11. Str::plural($value, $count = 2)
  12. // 生成更加真实的 "随机" 字母数字字符串.Str::random($length = 16)
  13. // 生成一个 "随机" 字母数字字符串.Str::quickRandom($length = 16)
  14. Str::upper($value)
  15. Str::title($value)
  16. Str::singular($value)
  17. Str::slug($title, $separator = '-')
  18. Str::snake($value, $delimiter = '_')
  19. Str::startsWith($haystack, $needles)
  20. Str::studly($value)
  21. Str::macro($name, $macro)

Helper

数组
  1. // 如果给定的键不存在于该数组,array_add 函数将给定的键值对加到数组中array_add($array, 'key', 'value');
  2. // 将数组的每一个数组折成单一数组array_collapse($array);
  3. // 函数返回两个数组,一个包含原本数组的键,另一个包含原本数组的值array_divide($array);
  4. // 把多维数组扁平化成一维数组,并用「点」式语法表示深度array_dot($array);
  5. // 从数组移除给定的键值对array_except($array, array('key'));
  6. // 返回数组中第一个通过为真测试的元素array_first($array, function($key, $value){}, $default);
  7. // 将多维数组扁平化成一维// ['Joe', 'PHP', 'Ruby'];array_flatten(['name' => 'Joe', 'languages' => ['PHP', 'Ruby']]);
  8. // 以「点」式语法从深度嵌套数组移除给定的键值对array_forget($array, 'foo');
  9. array_forget($array, 'foo.bar');
  10. // 使用「点」式语法从深度嵌套数组取回给定的值array_get($array, 'foo', 'default');
  11. array_get($array, 'foo.bar', 'default');
  12. // 使用「点」式语法检查给定的项目是否存在于数组中array_has($array, 'products.desk');
  13. // 从数组返回给定的键值对array_only($array, array('key'));
  14. // 从数组拉出一列给定的键值对array_pluck($array, 'key');
  15. // 从数组移除并返回给定的键值对array_pull($array, 'key');
  16. // 使用「点」式语法在深度嵌套数组中写入值array_set($array, 'key', 'value');
  17. array_set($array, 'key.subkey', 'value');
  18. // 借由给定闭包结果排序数组array_sort($array, function(){});
  19. // 使用 sort 函数递归排序数组array_sort_recursive();
  20. // 使用给定的闭包过滤数组array_where();
  21. // 返回给定数组的第一个元素head($array);
  22. // 返回给定数组的最后一个元素last($array);
路径
  1. // 取得 app 文件夹的完整路径app_path();
  2. // 取得项目根目录的完整路径base_path();
  3. // 取得应用配置目录的完整路径config_path();
  4. // 取得应用数据库目录的完整路径database_path();
  5. // 取得加上版本号的 Elixir 文件路径elixir();
  6. // 取得 public 目录的完整路径public_path();
  7. // 取得 storage 目录的完整路径storage_path();
字符串
  1. // 将给定的字符串转换成 驼峰式命名camel_case($value);
  2. // 返回不包含命名空间的类名称class_basename($class);
  3. class_basename($object);
  4. // 对给定字符串运行 htmlentitiese('<html>');
  5. // 判断字符串开头是否为给定内容starts_with('Foo bar.', 'Foo');
  6. // 判断给定字符串结尾是否为指定内容ends_with('Foo bar.', 'bar.');
  7. // 将给定的字符串转换成 蛇形命名snake_case('fooBar');
  8. // 限制字符串的字符数量str_limit();
  9. // 判断给定字符串是否包含指定内容str_contains('Hello foo bar.', 'foo');
  10. // 添加给定内容到字符串结尾,foo/bar/str_finish('foo/bar', '/');
  11. // 判断给定的字符串与给定的格式是否符合str_is('foo*', 'foobar');
  12. // 转换字符串成复数形str_plural('car');
  13. // 产生给定长度的随机字符串str_random(25);
  14. // 转换字符串成单数形。该函数目前仅支持英文str_singular('cars');
  15. // 从给定字符串产生网址友善的「slug」str_slug("Laravel 5 Framework", "-");
  16. // 将给定字符串转换成「首字大写命名」: FooBarstudly_case('foo_bar');
  17. // 根据你的本地化文件翻译给定的语句trans('foo.bar');
  18. // 根据后缀变化翻译给定的语句trans_choice('foo.bar', $count);
URLs and Links
  1. // 产生给定控制器行为网址action('FooController@method', $parameters);
  2. // 根据目前请求的协定(HTTP 或 HTTPS)产生资源文件网址asset('img/photo.jpg', $title, $attributes);
  3. // 根据 HTTPS 产生资源文件网址secure_asset('img/photo.jpg', $title, $attributes);
  4. // 产生给定路由名称网址route($route, $parameters, $absolute = true);
  5. // 产生给定路径的完整网址url('path', $parameters = array(), $secure = null);
Miscellaneous
  1. // 返回一个认证器实例。你可以使用它取代 Auth facadeauth()->user();
  2. // 产生一个重定向回应让用户回到之前的位置back();
  3. // 使用 Bcrypt 哈希给定的数值。你可以使用它替代 Hash facadebcrypt('my-secret-password');
  4. // 从给定的项目产生集合实例collect(['taylor', 'abigail']);
  5. // 取得设置选项的设置值config('app.timezone', $default);
  6. // 产生包含 CSRF 令牌内容的 HTML 表单隐藏字段{!! csrf_field() !!}
  7. // 取得当前 CSRF 令牌的内容$token = csrf_token();
  8. // 输出给定变量并结束脚本运行dd($value);
  9. // 取得环境变量值或返回默认值$env = env('APP_ENV');
  10. $env = env('APP_ENV', 'production');
  11. // 配送给定事件到所属的侦听器event(new UserRegistered($user));
  12. // 根据给定类、名称以及总数产生模型工厂建构器$user = factory(App\User::class)->make();
  13. // 产生拟造 HTTP 表单动作内容的 HTML 表单隐藏字段{!! method_field('delete') !!}
  14. // 取得快闪到 session 的旧有输入数值$value = old('value');
  15. $value = old('value', 'default');
  16. // 返回重定向器实例以进行 重定向return redirect('/home');
  17. // 取得目前的请求实例或输入的项目$value = request('key', $default = null)
  18. // 创建一个回应实例或获取一个回应工厂实例return response('Hello World', 200, $headers);
  19. // 可被用于取得或设置单一 session 内容$value = session('key');
  20. // 在没有传递参数时,将返回 session 实例$value = session()->get('key');
  21. session()->put('key', $value);
  22. // 返回给定数值value(function(){ return 'bar'; });
  23. // 取得视图 实例return view('auth.login');
  24. // 返回给定的数值$value = with(new Foo)->work();

Collection

  1. // 创建集合collect([1, 2, 3]);
  2. // 返回该集合所代表的底层数组:$collection->all();
  3. // 返回集合中所有项目的平均值:$collection->avg();
  4. // 将集合拆成多个给定大小的较小集合:$collection->chunk(4);
  5. // 将多个数组组成的集合折成单一数组集合:$collection->collapse();
  6. // 用来判断该集合是否含有指定的项目:$collection->contains('New York');
  7. // 返回该集合内的项目总数:$collection->count();
  8. // 遍历集合中的项目,并将之传入给定的回调函数:$collection = $collection->each(function ($item, $key) {
  9. });
  10. // 会创建一个包含第 n 个元素的新集合:$collection->every(4);
  11. // 传递偏移值作为第二个参数:$collection->every(4, 1);
  12. // 返回集合中排除指定键的所有项目:$collection->except(['price', 'discount']);
  13. // 以给定的回调函数筛选集合,只留下那些通过判断测试的项目:$filtered = $collection->filter(function ($item) {
  14. return $item > 2;
  15. });
  16. // 返回集合中,第一个通过给定测试的元素:collect([1, 2, 3, 4])->first(function ($key, $value) {
  17. return $value > 2;
  18. });
  19. // 将多维集合转为一维集合:$flattened = $collection->flatten();
  20. // 将集合中的键和对应的数值进行互换:$flipped = $collection->flip();
  21. // 以键自集合移除掉一个项目:$collection->forget('name');
  22. // 返回含有可以用来在给定页码显示项目的新集合:$chunk = $collection->forPage(2, 3);
  23. // 返回给定键的项目。如果该键不存在,则返回 null:$value = $collection->get('name');
  24. // 根据给定的键替集合内的项目分组:$grouped = $collection->groupBy('account_id');
  25. // 用来确认集合中是否含有给定的键:$collection->has('email');
  26. // 用来连接集合中的项目$collection->implode('product', ', ');
  27. // 移除任何给定数组或集合内所没有的数值:$intersect = $collection->intersect(['Desk', 'Chair', 'Bookcase']);
  28. // 假如集合是空的,isEmpty 方法会返回 true:collect([])->isEmpty();
  29. // 以给定键的值作为集合项目的键:$keyed = $collection->keyBy('product_id');
  30. // 传入回调函数,该函数会返回集合的键的值:$keyed = $collection->keyBy(function ($item) {
  31. return strtoupper($item['product_id']);
  32. });
  33. // 返回该集合所有的键:$keys = $collection->keys();
  34. // 返回集合中,最后一个通过给定测试的元素:$collection->last();
  35. // 遍历整个集合并将每一个数值传入给定的回调函数:$multiplied = $collection->map(function ($item, $key) {
  36. return $item * 2;
  37. });
  38. // 返回给定键的最大值:$max = collect([['foo' => 10], ['foo' => 20]])->max('foo');
  39. $max = collect([1, 2, 3, 4, 5])->max();
  40. // 将给定的数组合并进集合:$merged = $collection->merge(['price' => 100, 'discount' => false]);
  41. // 返回给定键的最小值:$min = collect([['foo' => 10], ['foo' => 20]])->min('foo');
  42. $min = collect([1, 2, 3, 4, 5])->min();
  43. // 返回集合中指定键的所有项目:$filtered = $collection->only(['product_id', 'name']);
  44. // 获取所有集合中给定键的值:$plucked = $collection->pluck('name');
  45. // 移除并返回集合最后一个项目:$collection->pop();
  46. // 在集合前面增加一个项目:$collection->prepend(0);
  47. // 传递第二个参数来设置前置项目的键:$collection->prepend(0, 'zero');
  48. // 以键从集合中移除并返回一个项目:$collection->pull('name');
  49. // 附加一个项目到集合后面:$collection->push(5);
  50. // put 在集合内设置一个给定键和数值:$collection->put('price', 100);
  51. // 从集合中随机返回一个项目:$collection->random();
  52. // 传入一个整数到 random。如果该整数大于 1,则会返回一个集合:$random = $collection->random(3);
  53. // 会将每次迭代的结果传入到下一次迭代:$total = $collection->reduce(function ($carry, $item) {
  54. return $carry + $item;
  55. });
  56. // 以给定的回调函数筛选集合:$filtered = $collection->reject(function ($item) {
  57. return $item > 2;
  58. });
  59. // 反转集合内项目的顺序:$reversed = $collection->reverse();
  60. // 在集合内搜索给定的数值并返回找到的键:$collection->search(4);
  61. // 移除并返回集合的第一个项目:$collection->shift();
  62. // 随机排序集合的项目:$shuffled = $collection->shuffle();
  63. // 返回集合从给定索引开始的一部分切片:$slice = $collection->slice(4);
  64. // 对集合排序:$sorted = $collection->sort();
  65. // 以给定的键排序集合:$sorted = $collection->sortBy('price');
  66. // 移除并返回从指定的索引开始的一小切片项目:$chunk = $collection->splice(2);
  67. // 返回集合内所有项目的总和:collect([1, 2, 3, 4, 5])->sum();
  68. // 返回有着指定数量项目的集合:$chunk = $collection->take(3);
  69. // 将集合转换成纯 PHP 数组:$collection->toArray();
  70. // 将集合转换成 JSON:$collection->toJson();
  71. // 遍历集合并对集合内每一个项目调用给定的回调函数:$collection->transform(function ($item, $key) {
  72. return $item * 2;
  73. });
  74. // 返回集合中所有唯一的项目:$unique = $collection->unique();
  75. // 返回键重设为连续整数的的新集合:$values = $collection->values();
  76. // 以一对给定的键/数值筛选集合:$filtered = $collection->where('price', 100);
  77. // 将集合与给定数组同样索引的值合并在一起:$zipped = $collection->zip([100, 200]);

Laravel 5 速查表的更多相关文章

  1. 简明 Git 命令速查表(中文版)

    原文引用地址:https://github.com/flyhigher139/Git-Cheat-Sheet/blob/master/Git%20Cheat%20Sheet-Zh.md在Github上 ...

  2. .htaccess下Flags速查表

    Flags是可选参数,当有多个标志同时出现时,彼此间以逗号分隔. 速查表: RewirteRule 标记 含义 描述 R Redirect 发出一个HTTP重定向 F Forbidden 禁止对URL ...

  3. Markdown 语法速查表

      Markdown 语法速查表 1 标题与文字格式 标题 # 这是 H1 <一级标题> ## 这是 H2 <二级标题> ###### 这是 H6 <六级标题> 文 ...

  4. jQuery API 3.1.0 速查表-打印版

    jQuery API 3.1.0 速查表-打印图,(API来自:http://jquery.cuishifeng.cn/index.html)

  5. java-Mysql-SQLServer数据类型匹配速查表

    java-Mysql-SQLServer数据类型匹配速查表 Mysql ************************************ 当前列 ClassName ColumnType Di ...

  6. python 下的数据结构与算法---2:大O符号与常用算法和数据结构的复杂度速查表

    目录: 一:大O记法 二:各函数高阶比较 三:常用算法和数据结构的复杂度速查表 四:常见的logn是怎么来的 一:大O记法 算法复杂度记法有很多种,其中最常用的就是Big O notation(大O记 ...

  7. HTML5速查表

    HTML5速查表 标签 描述 版本 属性 <!--...--> 定义注释 4 / 5 none <!DOCTYPE> 定义文档类型 4 / 5 none <a> 定 ...

  8. [翻译]Django速查表

    原文在此:https://code.djangoproject.com/wiki/DjangoCheatSheet Django速查表Django教程已经非常好了.这个速查表的作用是创建一个快速开始指 ...

  9. Java, C#, Swift语法对比速查表

    原文:Java, C#, Swift语法对比速查表   Java 8 C# 6 Swift 变量 类型 变量名; 类型 变量名; var 变量名 : 类型; 变量(类型推断) N/A var 变量名= ...

随机推荐

  1. Windows平台安装配置mysql数据库

    Windows平台安装配置mysql数据库 作者:Eric 微信:loveoracle11g 去下载mysql软件 https://www.mysql.com/downloads/ https://d ...

  2. SQL 生日得到年龄

    CREATE FUNCTION ufn_hr_getagefrombirthday ( @birthday DATE, @now DATE =NULL ) ) BEGIN IF (@now IS NU ...

  3. 著名java博客

    http://blog.csdn.net/net19880504/article/details/20807403

  4. python 常用技巧

    一.字符串与数值的转换 Python中字符串转换为数值: str_num = '99' num = int(str_num) 整型数转换为字符串: num = 99 str_num = str(num ...

  5. JavaScript数组方法--includes、indexOf、lastIndexOf

    我们继续吧! includes:includes() 方法用来判断一个数组是否包含一个指定的值,根据情况,如果包含则返回 true,否则返回false.还是先看看includes的用法吧 var ar ...

  6. BZOJ 3687: 简单题 bitset

    3687: 简单题 Time Limit: 10 Sec  Memory Limit: 512 MB[Submit][Status][Discuss] Description 小呆开始研究集合论了,他 ...

  7. mac与Windows系统支持软件汇总

    踩过的坑,记录下

  8. QMap迭代器

    QMap<int, QString> intToStr; intToStr[] = "test" for (auto iter = intToStr.begin(); ...

  9. idea Invalid bound statement (not found):

    一次 诡异的 idea Invalid bound statement (not found): 配置文件: mybatis.mapper-locations=classpath:mapper/*.x ...

  10. fibonacci数列-斐波那契数列-python编程

    未完待续~ 了解fibonacci数列: 斐波纳契数列(Fibonacci Sequence),又称黄金分割数列. 1,1,2,3,5,8,13,21,34,55,89,144,233,377,610 ...