国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

Laravel 速查表
顯示全部 1. Artisan 2. Auth 3. Blade 4. Cache 5. Collection 6. Composer 7. Config 8. Container 9. Cookie 10. DB 11. Environment 12. Event 13. File 14. Form 15. HTML 16. Helper 17. Input 18. Lang 19. Log 20. Mail 21. Model 22. Pagination 23. Queue 24. Redirect 25. Request 26. Response 27. Route 28. SSH 29. Schema 30. Security 31. Session 32. String 33. URL 34. UnitTest 35. Validation 36. View
導(dǎo)航

Laravel 速查表

Laravel 手冊

Artisan

// 在版本 5.1.11 新添加,見 http://d.laravel-china.org/docs/5.1/authorization#creating-policies
php artisan make:policy PostPolicy
// 針對命令顯示幫助信息
php artisan --help OR -h
// 抑制輸出信息
php artisan --quiet OR -q
// 打印 Laravel 的版本信息
php artisan --version OR -V
// 不詢問任何交互性的問題
php artisan --no-interaction OR -n
// 強(qiáng)制輸出 ANSI 格式
php artisan --ansi
// 禁止輸出 ANSI 格式
php artisan --no-ansi
// 顯示當(dāng)前命令行運行的環(huán)境
php artisan --env
// -v|vv|vvv 通過增加 v 的個數(shù)來控制命令行輸出內(nèi)容的詳盡情況: 1 個代表正常輸出, 2 個代表輸出更多消息, 3 個代表調(diào)試
php artisan --verbose
// 移除編譯優(yōu)化過的文件 (storage/frameworks/compiled.php)
php artisan clear-compiled
// 顯示當(dāng)前框架運行的環(huán)境
php artisan env
// 顯示某個命令的幫助信息
php artisan help
// 顯示所有可用的命令
php artisan list
// 進(jìn)入應(yīng)用交互模式
php artisan tinker
// 進(jìn)入維護(hù)模式
php artisan down
// 退出維護(hù)模式
php artisan up
// 優(yōu)化框架性能
 // --force    強(qiáng)制編譯已寫入文件 (storage/frameworks/compiled.php)
 // --psr      不對 Composer 的 dump-autoload 進(jìn)行優(yōu)化
php artisan optimize [--force] [--psr]
// 啟動內(nèi)置服務(wù)器
php artisan serve
// 更改默認(rèn)端口
php artisan serve --port 8080
// 使其在本地服務(wù)器外也可正常工作
php artisan serve --host 0.0.0.0
// 更改應(yīng)用命名空間
php artisan app:name namespace
// 清除過期的密碼重置令牌
php artisan auth:clear-resets
// 清空應(yīng)用緩存
php artisan cache:clear
// 創(chuàng)建緩存數(shù)據(jù)庫表 migration
php artisan cache:table
// 合并所有的配置信息為一個,提高加載速度
php artisan config:cache
// 移除配置緩存文件
php artisan config:clear
// 程序內(nèi)部調(diào)用 Artisan 命令
$exitCode = Artisan::call('config:cache');
// 運行所有的 seed 假數(shù)據(jù)生成類
 // --class      可以指定運行的類,默認(rèn)是: "DatabaseSeeder"
 // --database   可以指定數(shù)據(jù)庫
 // --force      當(dāng)處于生產(chǎn)環(huán)境時強(qiáng)制執(zhí)行操作
php artisan db:seed [--class[="..."]] [--database[="..."]] [--force]

// 基于注冊的信息,生成遺漏的 events 和 handlers
php artisan event:generate

// 生成新的處理器類
 // --command      需要處理器處理的命令類名字
php artisan handler:command [--command="..."] name
// 創(chuàng)建一個新的時間處理器類
 // --event        需要處理器處理的事件類名字
 // --queued       需要處理器使用隊列話處理的事件類名字
php artisan handler:event [--event="..."] [--queued] name

// 生成應(yīng)用的 key(會覆蓋)
php artisan key:generate

// 在默認(rèn)情況下, 這將創(chuàng)建未加入隊列的自處理命令
 // 通過 --handler 標(biāo)識來生成一個處理器, 用 --queued 來使其入隊列.
php artisan make:command [--handler] [--queued] name
// 創(chuàng)建一個新的 Artisan 命令
 //  --command     命令被調(diào)用的名稱。 (默認(rèn)為: "command:name")
php artisan make:console [--command[="..."]] name
// 創(chuàng)建一個新的資源控制器
 // --plain      生成一個空白的控制器類
php artisan make:controller [--plain] name
php artisan make:controller App\\Admin\\Http\\Controllers\\DashboardController
// 創(chuàng)建一個新的事件類
php artisan make:event name
// 創(chuàng)建一個新的中間件類
php artisan make:middleware name
// 創(chuàng)建一個新的遷移文件
 // --create     將被創(chuàng)建的數(shù)據(jù)表.
 // --table      將被遷移的數(shù)據(jù)表.
php artisan make:migration [--create[="..."]] [--table[="..."]] name
// 創(chuàng)建一個新的 Eloquent 模型類
php artisan make:model name
// 創(chuàng)建一個新的服務(wù)提供者類
php artisan make:provider name
// 創(chuàng)建一個新的表單請求類
php artisan make:request name
// 數(shù)據(jù)庫遷移
 // --database   指定數(shù)據(jù)庫連接(下同)
 // --force      當(dāng)處于生產(chǎn)環(huán)境時強(qiáng)制執(zhí)行,不詢問(下同)
 // --path       指定單獨遷移文件地址
 // --pretend    把將要運行的 SQL 語句打印出來(下同)
 // --seed       Seed 任務(wù)是否需要被重新運行(下同)
php artisan migrate [--database[="..."]] [--force] [--path[="..."]] [--pretend] [--seed]
// 創(chuàng)建遷移數(shù)據(jù)庫表
php artisan migrate:install [--database[="..."]]
// 重置并重新運行所有的 migrations
 // --seeder     指定主 Seeder 的類名
php artisan migrate:refresh [--database[="..."]] [--force] [--seed] [--seeder[="..."]]
// 回滾所有的數(shù)據(jù)庫遷移
php artisan migrate:reset [--database[="..."]] [--force] [--pretend]
// 回滾最最近一次運行的遷移任務(wù)
php artisan migrate:rollback [--database[="..."]] [--force] [--pretend]
// migrations 數(shù)據(jù)庫表信息
php artisan migrate:status
// 為隊列數(shù)據(jù)庫表創(chuàng)建一個新的遷移
php artisan queue:table
// 監(jiān)聽指定的隊列
 // --queue      被監(jiān)聽的隊列
 // --delay      給執(zhí)行失敗的任務(wù)設(shè)置延時時間 (默認(rèn)為零: 0)
 // --memory     內(nèi)存限制大小,單位為 MB (默認(rèn)為: 128)
 // --timeout    指定任務(wù)運行超時秒數(shù) (默認(rèn)為: 60)
 // --sleep      等待檢查隊列任務(wù)的秒數(shù) (默認(rèn)為: 3)
 // --tries      任務(wù)記錄失敗重試次數(shù) (默認(rèn)為: 0)
php artisan queue:listen [--queue[="..."]] [--delay[="..."]] [--memory[="..."]] [--timeout[="..."]] [--sleep[="..."]] [--tries[="..."]] [connection]
// 查看所有執(zhí)行失敗的隊列任務(wù)
php artisan queue:failed
// 為執(zhí)行失敗的數(shù)據(jù)表任務(wù)創(chuàng)建一個遷移
php artisan queue:failed-table
// 清除所有執(zhí)行失敗的隊列任務(wù)
php artisan queue:flush
// 刪除一個執(zhí)行失敗的隊列任務(wù)
php artisan queue:forget
// 在當(dāng)前的隊列任務(wù)執(zhí)行完畢后, 重啟隊列的守護(hù)進(jìn)程
php artisan queue:restart
// 對指定 id 的執(zhí)行失敗的隊列任務(wù)進(jìn)行重試(id: 失敗隊列任務(wù)的 ID)
php artisan queue:retry id
// 指定訂閱 Iron.io 隊列的鏈接
 // queue: Iron.io 的隊列名稱.
 // url: 將被訂閱的 URL.
 // --type       指定隊列的推送類型.
php artisan queue:subscribe [--type[="..."]] queue url
// 處理下一個隊列任務(wù)
 // --queue      被監(jiān)聽的隊列
 // --daemon     在后臺模式運行
 // --delay      給執(zhí)行失敗的任務(wù)設(shè)置延時時間 (默認(rèn)為零: 0)
 // --force      強(qiáng)制在「維護(hù)模式下」運行
 // --memory     內(nèi)存限制大小,單位為 MB (默認(rèn)為: 128)
 // --sleep      當(dāng)沒有任務(wù)處于有效狀態(tài)時, 設(shè)置其進(jìn)入休眠的秒數(shù) (默認(rèn)為: 3)
 // --tries      任務(wù)記錄失敗重試次數(shù) (默認(rèn)為: 0)
php artisan queue:work [--queue[="..."]] [--daemon] [--delay[="..."]] [--force] [--memory[="..."]] [--sleep[="..."]] [--tries[="..."]] [connection]

// 生成路由緩存文件來提升路由效率
php artisan route:cache
// 移除路由緩存文件
php artisan route:clear
// 顯示已注冊過的路由
php artisan route:list

// 運行計劃命令
php artisan schedule:run

// 為 session 數(shù)據(jù)表生成遷移文件
php artisan session:table

// 從 vendor 的擴(kuò)展包中發(fā)布任何可發(fā)布的資源
 // --force        重寫所有已存在的文件
 // --provider     指定你想要發(fā)布資源文件的服務(wù)提供者
 // --tag          指定你想要發(fā)布標(biāo)記資源.
php artisan vendor:publish [--force] [--provider[="..."]] [--tag[="..."]]
php artisan tail [--path[="..."]] [--lines[="..."]] [connection]

Pagination

// 自動處理分頁邏輯
 Model::paginate(15);
Model::where('cars', 2)->paginate(15);
// 使用簡單模板 - 只有 "上一頁" 或 "下一頁" 鏈接
 Model::where('cars', 2)->simplePaginate(15);
// 手動分頁
 Paginator::make($items, $totalItems, $perPage);
// 在頁面打印分頁導(dǎo)航欄
$variable->links();

Lang

App::setLocale('en');
Lang::get('messages.welcome');
Lang::get('messages.welcome', array('foo' => 'Bar'));
Lang::has('messages.welcome');
Lang::choice('messages.apples', 10);
// Lang::get 的別名
trans('messages.welcome');

File

File::exists('path');
File::get('path');
File::getRemote('path');
// 獲取文件內(nèi)容
 File::getRequire('path');
// 獲取文件內(nèi)容, 僅能引入一次
 File::requireOnce('path');
// 將內(nèi)容寫入文件
 File::put('path', 'contents');
// 將內(nèi)容添加在文件原內(nèi)容后
 File::append('path', 'data');
// 通過給定的路徑來刪除文件
 File::delete('path');
// 將文件移動到新目錄下
 File::move('path', 'target');
// Copy a file to a new location
 // 將文件復(fù)制到新目錄下
 File::copy('path', 'target');
// 從文件的路徑地址提取文件的擴(kuò)展
 File::extension('path');
// 獲取文件類型
 File::type('path');
// 獲取文件大小
 File::size('path');
// 獲取文件的最后修改時間
 File::lastModified('path');
// 判斷給定的路徑是否是文件目錄
 File::isDirectory('directory');
// 判斷給定的路徑是否是可寫入的
 File::isWritable('path');
// 判斷給定的路徑是否是文件
 File::isFile('file');
// 查找能被匹配到的路徑名
 File::glob($patterns, $flag);
// Get an array of all files in a directory.
 // 獲取一個目錄下的所有文件, 以數(shù)組類型返回
 File::files('directory');
// 獲取一個目錄下的所有文件 (遞歸).
 File::allFiles('directory');
// 獲取一個目錄內(nèi)的目錄
 File::directories('directory');
// 創(chuàng)建一個目錄
 File::makeDirectory('path',  $mode = 0777, $recursive = false);
// 將文件夾從一個目錄復(fù)制到另一個目錄下
 File::copyDirectory('directory', 'destination', $options = null);
// 遞歸式刪除目錄
 File::deleteDirectory('directory', $preserve = false);
// 清空指定目錄的所有文件和文件夾
 File::cleanDirectory('directory');

SSH

Executing Commands

SSH::run(array $commands);
// 指定 remote, 否則將使用默認(rèn)值
SSH::into($remote)->run(array $commands);
SSH::run(array $commands, function($line)
{
  echo $line.PHP_EOL;
});

任務(wù)

// 定義任務(wù)
SSH::define($taskName, array $commands);
// 執(zhí)行任務(wù)
SSH::task($taskName, function($line)
{
  echo $line.PHP_EOL;
});

SFTP 上傳

SSH::put($localFile, $remotePath);
SSH::putString($string, $remotePath);

Schema

// 創(chuàng)建指定數(shù)據(jù)表
 Schema::create('table', function($table)
{
  $table->increments('id');
});
// 指定一個連接
 Schema::connection('foo')->create('table', function($table){});
// 通過給定的名稱來重命名數(shù)據(jù)表
 Schema::rename($from, $to);
// 移除指定數(shù)據(jù)表
 Schema::drop('table');
// 當(dāng)數(shù)據(jù)表存在時, 將指定數(shù)據(jù)表移除
 Schema::dropIfExists('table');
// 判斷數(shù)據(jù)表是否存在
 Schema::hasTable('table');
// 判斷數(shù)據(jù)表是否有該列
 Schema::hasColumn('table', 'column');
// 更新一個已存在的數(shù)據(jù)表
 Schema::table('table', function($table){});
// 重命名數(shù)據(jù)表的列
$table->renameColumn('from', 'to');
// 移除指定的數(shù)據(jù)表列
$table->dropColumn(string|array);
// 指定數(shù)據(jù)表使用的存儲引擎
$table->engine = 'InnoDB';
// 字段順序,只能在 MySQL 中才能用
$table->string('name')->after('email');

索引

$table->string('column')->unique();
$table->primary('column');
// 創(chuàng)建一個雙主鍵
$table->primary(array('first', 'last'));
$table->unique('column');
$table->unique('column', 'key_name');
// 創(chuàng)建一個雙唯一性索引
$table->unique(array('first', 'last'));
$table->unique(array('first', 'last'), 'key_name');
$table->index('column');
$table->index('column', 'key_name');
// 創(chuàng)建一個雙索引
$table->index(array('first', 'last'));
$table->index(array('first', 'last'), 'key_name');
$table->dropPrimary(array('column'));
$table->dropPrimary('table_column_primary');
$table->dropUnique(array('column'));
$table->dropUnique('table_column_unique');
$table->dropIndex(array('column'));
$table->dropIndex('table_column_index');

外鍵

$table->foreign('user_id')->references('id')->on('users');
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade'|'restrict'|'set null'|'no action');
$table->foreign('user_id')->references('id')->on('users')->onUpdate('cascade'|'restrict'|'set null'|'no action');
$table->dropForeign(array('user_id'));
$table->dropForeign('posts_user_id_foreign');

字段類型

// 自增
$table->increments('id');
$table->bigIncrements('id');

// 數(shù)字
$table->integer('votes');
$table->tinyInteger('votes');
$table->smallInteger('votes');
$table->mediumInteger('votes');
$table->bigInteger('votes');
$table->float('amount');
$table->double('column', 15, 8);
$table->decimal('amount', 5, 2);

// 字符串和文本
$table->char('name', 4);
$table->string('email');
$table->string('name', 100);
$table->text('description');
$table->mediumText('description');
$table->longText('description');

// 日期和時間
$table->date('created_at');
$table->dateTime('created_at');
$table->time('sunrise');
$table->timestamp('added_on');
// Adds created_at and updated_at columns
 // 添加 created_at 和 updated_at 行
$table->timestamps();
$table->nullableTimestamps();

// 其它類型
$table->binary('data');
$table->boolean('confirmed');
// 為軟刪除添加 deleted_at 字段
$table->softDeletes();
$table->enum('choices', array('foo', 'bar'));
// 添加 remember_token 為 VARCHAR(100) NULL
$table->rememberToken();
// 添加整型的 parent_id 和字符串類型的 parent_type
$table->morphs('parent');
->nullable()
->default($value)
->unsigned()

Auth

用戶認(rèn)證

// 判斷當(dāng)前用戶是否已認(rèn)證(是否已登錄)
 Auth::check();
// 獲取當(dāng)前的認(rèn)證用戶
 Auth::user();
// 獲取當(dāng)前的認(rèn)證用戶的 ID(未登錄情況下會報錯)
 Auth::id();
// 通過給定的信息來嘗試對用戶進(jìn)行認(rèn)證(成功后會自動啟動會話)
 Auth::attempt(['email' => $email, 'password' => $password]);
// 通過 Auth::attempt() 傳入 true 值來開啟 '記住我' 功能
 Auth::attempt($credentials, true);
// 只針對一次的請求來認(rèn)證用戶
 Auth::once($credentials);
// 登錄一個指定用戶到應(yīng)用上
 Auth::login(User::find(1));
// 登錄指定用戶 ID 的用戶到應(yīng)用上
 Auth::loginUsingId(1);
// 使用戶退出登錄(清除會話)
 Auth::logout();
// 驗證用戶憑證
 Auth::validate($credentials);
// Attempt to authenticate using HTTP Basic Auth
 // 使用 HTTP 的基本認(rèn)證方式來認(rèn)證
 Auth::basic('username');
// Perform a stateless HTTP Basic login attempt
 // 執(zhí)行「HTTP Basic」登錄嘗試
 Auth::onceBasic();
// 發(fā)送密碼重置提示給用戶
 Password::remind($credentials, function($message, $user){});

用戶授權(quán)

// 定義權(quán)限
 Gate::define('update-post', 'Class@method');
Gate::define('update-post', function ($user, $post) {...});
// 傳遞多個參數(shù)
 Gate::define('delete-comment', function ($user, $post, $comment) {});

// 檢查權(quán)限
 Gate::denies('update-post', $post);
Gate::allows('update-post', $post);
Gate::check('update-post', $post);
// 指定用戶進(jìn)行檢查
 Gate::forUser($user)->allows('update-post', $post);
// 在 User 模型下,使用 Authorizable trait
 User::find(1)->can('update-post', $post);
User::find(1)->cannot('update-post', $post);

// 攔截所有檢查
 Gate::before(function ($user, $ability) {});
Gate::after(function ($user, $ability) {});

// Blade 模板語法
 @can('update-post', $post)
@endcan
// 支持 else 表達(dá)式
 @can('update-post', $post)
@else
@endcan

// 生成一個新的策略
php artisan make:policy PostPolicy
// `policy` 幫助函數(shù)
policy($post)->update($user, $post)

// 控制器授權(quán)
$this->authorize('update', $post);
// 指定用戶 $user 授權(quán)
$this->authorizeForUser($user, 'update', $post);

Form

Form::open(array('url' => 'foo/bar', 'method' => 'PUT'));
Form::open(array('route' => 'foo.bar'));
Form::open(array('route' => array('foo.bar', $parameter)));
Form::open(array('action' => 'FooController@method'));
Form::open(array('action' => array('FooController@method', $parameter)));
Form::open(array('url' => 'foo/bar', 'files' => true));
Form::close();
Form::token();
Form::model($foo, array('route' => array('foo.bar', $foo->bar)));

表單元素

Form::label('id', 'Description');
Form::label('id', 'Description', array('class' => 'foo'));
Form::text('name');
Form::text('name', $value);
Form::text('name', $value, array('class' => 'name'));
Form::textarea('name');
Form::textarea('name', $value);
Form::textarea('name', $value, array('class' => 'name'));
Form::hidden('foo', $value);
Form::password('password');
Form::password('password', array('placeholder' => 'Password'));
Form::email('name', $value, array());
Form::file('name', array('class' => 'name'));
Form::checkbox('name', 'value');
// 生成一個被選中的復(fù)選框
 Form::checkbox('name', 'value', true, array('class' => 'name'));
Form::radio('name', 'value');
// 生成一個被選中的單選框
 Form::radio('name', 'value', true, array('class' => 'name'));
Form::select('name', array('key' => 'value'));
Form::select('name', array('key' => 'value'), 'key', array('class' => 'name'));
Form::selectRange('range', 1, 10);
Form::selectYear('year', 2011, 2015);
Form::selectMonth('month');
Form::submit('Submit!', array('class' => 'name'));
Form::button('name', array('class' => 'name'));
Form::macro('fooField', function()
{
return '<input type="custom"/>';
});
Form::fooField();

Helper

數(shù)組

// 如果給定的鍵不存在于該數(shù)組,array_add 函數(shù)將給定的鍵值對加到數(shù)組中
array_add($array, 'key', 'value');
// 將數(shù)組的每一個數(shù)組折成單一數(shù)組
array_collapse($array);
// 函數(shù)返回兩個數(shù)組,一個包含原本數(shù)組的鍵,另一個包含原本數(shù)組的值
array_divide($array);
// 把多維數(shù)組扁平化成一維數(shù)組,并用「點」式語法表示深度
array_dot($array);
// 從數(shù)組移除給定的鍵值對
array_except($array, array('key'));
// 返回數(shù)組中第一個通過為真測試的元素
array_first($array, function($key, $value){}, $default);
// 將多維數(shù)組扁平化成一維
 // ['Joe', 'PHP', 'Ruby'];
array_flatten(['name' => 'Joe', 'languages' => ['PHP', 'Ruby']]);
// 以「點」式語法從深度嵌套數(shù)組移除給定的鍵值對
array_forget($array, 'foo');
array_forget($array, 'foo.bar');
// 使用「點」式語法從深度嵌套數(shù)組取回給定的值
array_get($array, 'foo', 'default');
array_get($array, 'foo.bar', 'default');
// 使用「點」式語法檢查給定的項目是否存在于數(shù)組中
array_has($array, 'products.desk');
// 從數(shù)組返回給定的鍵值對
array_only($array, array('key'));
// 從數(shù)組拉出一列給定的鍵值對
array_pluck($array, 'key');
// 從數(shù)組移除并返回給定的鍵值對
array_pull($array, 'key');
// 使用「點」式語法在深度嵌套數(shù)組中寫入值
array_set($array, 'key', 'value');
array_set($array, 'key.subkey', 'value');
// 借由給定閉包結(jié)果排序數(shù)組
array_sort($array, function(){});
// 使用 sort 函數(shù)遞歸排序數(shù)組
array_sort_recursive();
// 使用給定的閉包過濾數(shù)組
array_where();
// 返回給定數(shù)組的第一個元素
head($array);
// 返回給定數(shù)組的最后一個元素
 last($array);

路徑

// 取得 app 文件夾的完整路徑
app_path();
// 取得項目根目錄的完整路徑
base_path();
// 取得應(yīng)用配置目錄的完整路徑
config_path();
// 取得應(yīng)用數(shù)據(jù)庫目錄的完整路徑
database_path();
// 取得加上版本號的 Elixir 文件路徑
elixir();
// 取得 public 目錄的完整路徑
public_path();
// 取得 storage 目錄的完整路徑
storage_path();

字符串

// 將給定的字符串轉(zhuǎn)換成 駝峰式命名
camel_case($value);
// 返回不包含命名空間的類名稱
class_basename($class);
class_basename($object);
// 對給定字符串運行 htmlentities
e('<html>');
// 判斷字符串開頭是否為給定內(nèi)容
starts_with('Foo bar.', 'Foo');
// 判斷給定字符串結(jié)尾是否為指定內(nèi)容
ends_with('Foo bar.', 'bar.');
// 將給定的字符串轉(zhuǎn)換成 蛇形命名
snake_case('fooBar');
// 限制字符串的字符數(shù)量
str_limit();
// 判斷給定字符串是否包含指定內(nèi)容
str_contains('Hello foo bar.', 'foo');
// 添加給定內(nèi)容到字符串結(jié)尾,foo/bar/
str_finish('foo/bar', '/');
// 判斷給定的字符串與給定的格式是否符合
str_is('foo*', 'foobar');
// 轉(zhuǎn)換字符串成復(fù)數(shù)形
str_plural('car');
// 產(chǎn)生給定長度的隨機(jī)字符串
str_random(25);
// 轉(zhuǎn)換字符串成單數(shù)形。該函數(shù)目前僅支持英文
str_singular('cars');
// 從給定字符串產(chǎn)生網(wǎng)址友善的「slug」
str_slug("Laravel 5 Framework", "-");
// 將給定字符串轉(zhuǎn)換成「首字大寫命名」: FooBar
studly_case('foo_bar');
// 根據(jù)你的本地化文件翻譯給定的語句
trans('foo.bar');
// 根據(jù)后綴變化翻譯給定的語句
trans_choice('foo.bar', $count);

URLs and Links

// 產(chǎn)生給定控制器行為網(wǎng)址
action('FooController@method', $parameters);
// 根據(jù)目前請求的協(xié)定(HTTP 或 HTTPS)產(chǎn)生資源文件網(wǎng)址
asset('img/photo.jpg', $title, $attributes);
// 根據(jù) HTTPS 產(chǎn)生資源文件網(wǎng)址
secure_asset('img/photo.jpg', $title, $attributes);
// 產(chǎn)生給定路由名稱網(wǎng)址
route($route, $parameters, $absolute = true);
// 產(chǎn)生給定路徑的完整網(wǎng)址
url('path', $parameters = array(), $secure = null);

其他

// 返回一個認(rèn)證器實例。你可以使用它取代 Auth facade
auth()->user();
// 產(chǎn)生一個重定向回應(yīng)讓用戶回到之前的位置
back();
// 使用 Bcrypt 哈希給定的數(shù)值。你可以使用它替代 Hash facade
bcrypt('my-secret-password');
// 從給定的項目產(chǎn)生集合實例
collect(['taylor', 'abigail']);
// 取得設(shè)置選項的設(shè)置值
config('app.timezone', $default);
// 產(chǎn)生包含 CSRF 令牌內(nèi)容的 HTML 表單隱藏字段
 {!! csrf_field() !!}
// 取得當(dāng)前 CSRF 令牌的內(nèi)容
$token = csrf_token();
// 輸出給定變量并結(jié)束腳本運行
dd($value);
// 取得環(huán)境變量值或返回默認(rèn)值
$env = env('APP_ENV');
$env = env('APP_ENV', 'production');
// 配送給定事件到所屬的偵聽器
 event(new UserRegistered($user));
// 根據(jù)給定類、名稱以及總數(shù)產(chǎn)生模型工廠建構(gòu)器
$user = factory(App\User::class)->make();
// 產(chǎn)生擬造 HTTP 表單動作內(nèi)容的 HTML 表單隱藏字段
 {!! method_field('delete') !!}
// 取得快閃到 session 的舊有輸入數(shù)值
$value = old('value');
$value = old('value', 'default');
// 返回重定向器實例以進(jìn)行 重定向
 return redirect('/home');
// 取得目前的請求實例或輸入的項目
$value = request('key', $default = null)
// 創(chuàng)建一個回應(yīng)實例或獲取一個回應(yīng)工廠實例
 return response('Hello World', 200, $headers);
// 可被用于取得或設(shè)置單一 session 內(nèi)容
$value = session('key');
// 在沒有傳遞參數(shù)時,將返回 session 實例
$value = session()->get('key');
session()->put('key', $value);
// 返回給定數(shù)值
value(function(){ return 'bar'; });
// 取得視圖 實例
 return view('auth.login');
// 返回給定的數(shù)值
$value = with(new Foo)->work();

Composer

composer create-project laravel/laravel folder_name
composer install
composer update
composer dump-autoload [--optimize]
composer self-update
composer require [options] [--] [vendor/packages]...

Environment

$environment = app()->environment();
$environment = App::environment();
$environment = $app->environment();
// 判斷當(dāng)環(huán)境是否為 local
 if ($app->environment('local')){}
// 判斷當(dāng)環(huán)境是否為 local 或 staging...
 if ($app->environment('local', 'staging')){}

Log

// 記錄器提供了 7 種在 RFC 5424 標(biāo)準(zhǔn)內(nèi)定義的記錄等級:
 // debug, info, notice, warning, error, critical, and alert.
 Log::info('info');
Log::info('info',array('context'=>'additional info'));
Log::error('error');
Log::warning('warning');
// 獲取 monolog 實例
 Log::getMonolog();
// 添加監(jiān)聽器
 Log::listen(function($level, $message, $context) {});

記錄 SQL 查詢語句

// 開啟 log
DB::connection()->enableQueryLog();
// 獲取已執(zhí)行的查詢數(shù)組
DB::getQueryLog();

URL

URL::full();
URL::current();
URL::previous();
URL::to('foo/bar', $parameters, $secure);
URL::action('NewsController@item', ['id'=>123]);
// 需要在適當(dāng)?shù)拿臻g內(nèi)
URL::action('Auth\AuthController@logout');
URL::action('FooController@method', $parameters, $absolute);
URL::route('foo', $parameters, $absolute);
URL::secure('foo/bar', $parameters);
URL::asset('css/foo.css', $secure);
URL::secureAsset('css/foo.css');
URL::isValidUrl('http://example.com');
URL::getRequest();
URL::setRequest($request);

Event

Event::fire('foo.bar', array($bar));
// 注冊一個事件監(jiān)聽器.
 // void listen(string|array $events, mixed $listener, int $priority)
 Event::listen('App\Events\UserSignup', function($bar){});
Event::listen('foo.*', function($bar){});
Event::listen('foo.bar', 'FooHandler', 10);
Event::listen('foo.bar', 'BarHandler', 5);
// 你可以直接在處理邏輯中返回 false 來停止一個事件的傳播.
 Event::listen('foor.bar', function($event){ return false; });
Event::subscribe('UserEventHandler');

DB

基本使用

DB::connection('connection_name');
// 運行數(shù)據(jù)庫查詢語句
$results = DB::select('select * from users where id = ?', [1]);
$results = DB::select('select * from users where id = :id', ['id' => 1]);
// 運行普通語句
DB::statement('drop table users');
// 監(jiān)聽查詢事件
DB::listen(function($sql, $bindings, $time){ code_here; });
// 數(shù)據(jù)庫事務(wù)處理
DB::transaction(function()
{
DB::table('users')->update(['votes' => 1]);
DB::table('posts')->delete();
});
DB::beginTransaction();
DB::rollBack();
DB::commit();

查詢語句構(gòu)造器?

// 取得數(shù)據(jù)表的所有行
DB::table('name')->get();
// 取數(shù)據(jù)表的部分?jǐn)?shù)據(jù)
DB::table('users')->chunk(100, function($users)
{
  foreach ($users as $user)
  {

//
 }
});
// 取回數(shù)據(jù)表的第一條數(shù)據(jù)
$user = DB::table('users')->where('name', 'John')->first();
DB::table('name')->first();
// 從單行中取出單列數(shù)據(jù)
$name = DB::table('users')->where('name', 'John')->pluck('name');
DB::table('name')->pluck('column');
// 取多行數(shù)據(jù)的「列數(shù)據(jù)」數(shù)組
$roles = DB::table('roles')->lists('title');
$roles = DB::table('roles')->lists('title', 'name');
// 指定一個選擇字句
$users = DB::table('users')->select('name', 'email')->get();
$users = DB::table('users')->distinct()->get();
$users = DB::table('users')->select('name as user_name')->get();
// 添加一個選擇字句到一個已存在的查詢語句中
$query = DB::table('users')->select('name');
$users = $query->addSelect('age')->get();
// 使用 Where 運算符
$users = DB::table('users')->where('votes', '>', 100)->get();
$users = DB::table('users')
              ->where('votes', '>', 100)
              ->orWhere('name', 'John')
              ->get();
$users = DB::table('users')
      ->whereBetween('votes', [1, 100])->get();
$users = DB::table('users')
      ->whereNotBetween('votes', [1, 100])->get();
$users = DB::table('users')
      ->whereIn('id', [1, 2, 3])->get();
$users = DB::table('users')
      ->whereNotIn('id', [1, 2, 3])->get();
$users = DB::table('users')
      ->whereNull('updated_at')->get();
DB::table('name')->whereNotNull('column')->get();
// 動態(tài)的 Where 字句
$admin = DB::table('users')->whereId(1)->first();
$john = DB::table('users')
      ->whereIdAndEmail(2, 'john@doe.com')
      ->first();
$jane = DB::table('users')
      ->whereNameOrAge('Jane', 22)
      ->first();
// Order By, Group By, 和 Having
$users = DB::table('users')
      ->orderBy('name', 'desc')
      ->groupBy('count')
      ->having('count', '>', 100)
      ->get();
DB::table('name')->orderBy('column')->get();
DB::table('name')->orderBy('column','desc')->get();
DB::table('name')->having('count', '>', 100)->get();
// 偏移 & 限制
$users = DB::table('users')->skip(10)->take(5)->get();

Joins?

// 基本的 Join 聲明語句
DB::table('users')
    ->join('contacts', 'users.id', '=', 'contacts.user_id')
    ->join('orders', 'users.id', '=', 'orders.user_id')
    ->select('users.id', 'contacts.phone', 'orders.price')
    ->get();
// Left Join 聲明語句
DB::table('users')
->leftJoin('posts', 'users.id', '=', 'posts.user_id')
->get();
// select * from users where name = 'John' or (votes > 100 and title <> 'Admin')
DB::table('users')
    ->where('name', '=', 'John')
    ->orWhere(function($query)
    {
        $query->where('votes', '>', 100)
              ->where('title', '<>', 'Admin');
    })
    ->get();

聚合?

$users = DB::table('users')->count();
$price = DB::table('orders')->max('price');
$price = DB::table('orders')->min('price');
$price = DB::table('orders')->avg('price');
$total = DB::table('users')->sum('votes');

原始表達(dá)句

$users = DB::table('users')
                   ->select(DB::raw('count(*) as user_count, status'))
                   ->where('status', '<>', 1)
                   ->groupBy('status')
                   ->get();
// 返回行
DB::select('select * from users where id = ?', array('value'));
DB::insert('insert into foo set bar=2');
DB::update('update foo set bar=2');
DB::delete('delete from bar');
// 返回 void
DB::statement('update foo set bar=2');
// 在聲明語句中加入原始的表達(dá)式
DB::table('name')->select(DB::raw('count(*) as count, column2'))->get();

Inserts / Updates / Deletes / Unions / Pessimistic Locking

// 插入
DB::table('users')->insert(
  ['email' => 'john@example.com', 'votes' => 0]
);
$id = DB::table('users')->insertGetId(
  ['email' => 'john@example.com', 'votes' => 0]
);
DB::table('users')->insert([
  ['email' => 'taylor@example.com', 'votes' => 0],
  ['email' => 'dayle@example.com', 'votes' => 0]
]);
// 更新
DB::table('users')
          ->where('id', 1)
          ->update(['votes' => 1]);
DB::table('users')->increment('votes');
DB::table('users')->increment('votes', 5);
DB::table('users')->decrement('votes');
DB::table('users')->decrement('votes', 5);
DB::table('users')->increment('votes', 1, ['name' => 'John']);
// 刪除
DB::table('users')->where('votes', '<', 100)->delete();
DB::table('users')->delete();
DB::table('users')->truncate();
// 集合
 // unionAll() 方法也是可供使用的,調(diào)用方式與 union 相似
$first = DB::table('users')->whereNull('first_name');
$users = DB::table('users')->whereNull('last_name')->union($first)->get();
// 消極鎖
DB::table('users')->where('votes', '>', 100)->sharedLock()->get();
DB::table('users')->where('votes', '>', 100)->lockForUpdate()->get();

UnitTest

安裝和運行

// 將其加入到 composer.json 并更新:
composer require "phpunit/phpunit:4.0.*"
// 運行測試 (在項目根目錄下運行)
 ./vendor/bin/phpunit

斷言

$this->assertTrue(true);
$this->assertEquals('foo', $bar);
$this->assertCount(1,$times);
$this->assertResponseOk();
$this->assertResponseStatus(403);
$this->assertRedirectedTo('foo');
$this->assertRedirectedToRoute('route.name');
$this->assertRedirectedToAction('Controller@method');
$this->assertViewHas('name');
$this->assertViewHas('age', $value);
$this->assertSessionHasErrors();
// 由單個 key 值來假定 session 有錯誤...
$this->assertSessionHasErrors('name');
// 由多個 key 值來假定 session 有錯誤...
$this->assertSessionHasErrors(array('name', 'age'));
$this->assertHasOldInput();

訪問路由

$response = $this->call($method, $uri, $parameters, $files, $server, $content);
$response = $this->callSecure('GET', 'foo/bar');
$this->session(['foo' => 'bar']);
$this->flushSession();
$this->seed();
$this->seed($connection);

Input

Input::get('key');
// 指定默認(rèn)值
 Input::get('key', 'default');
Input::has('key');
Input::all();
// 只取回 'foo' 和 'bar',返回數(shù)組
 Input::only('foo', 'bar');
// 取除了 'foo' 的所有用戶輸入數(shù)組
 Input::except('foo');
Input::flush();

會話周期內(nèi) Input

// 清除會話周期內(nèi)的輸入
 Input::flash();
// 清除會話周期內(nèi)的指定輸入
 Input::flashOnly('foo', 'bar');
// 清除會話周期內(nèi)的除了指定的其他輸入
 Input::flashExcept('foo', 'baz');
// 取回一個舊的輸入條目
 Input::old('key','default_value');

Files

// 使用一個已上傳的文件
 Input::file('filename');
// 判斷文件是否已上傳
 Input::hasFile('filename');
// 獲取文件屬性
 Input::file('name')->getRealPath();
Input::file('name')->getClientOriginalName();
Input::file('name')->getClientOriginalExtension();
Input::file('name')->getSize();
Input::file('name')->getMimeType();
// 移動一個已上傳的文件
 Input::file('name')->move($destinationPath);
// 移動一個已上傳的文件,并設(shè)置新的名字
 Input::file('name')->move($destinationPath, $fileName);

Session

Session::get('key');
// 從會話中讀取一個條目
 Session::get('key', 'default');
Session::get('key', function(){ return 'default'; });
// 獲取 session 的 ID
 Session::getId();
// 增加一個會話鍵值數(shù)據(jù)
 Session::put('key', 'value');
// 將一個值加入到 session 的數(shù)組中
 Session::push('foo.bar','value');
// 返回 session 的所有條目
 Session::all();
// 檢查 session 里是否有此條目
 Session::has('key');
// 從 session 中移除一個條目
 Session::forget('key');
// 從 session 中移除所有條目
 Session::flush();
// 生成一個新的 session 標(biāo)識符
 Session::regenerate();
// 把一條數(shù)據(jù)暫存到 session 中
 Session::flash('key', 'value');
// 清空所有的暫存數(shù)據(jù)
 Session::reflash();
// 重新暫存當(dāng)前暫存數(shù)據(jù)的子集
 Session::keep(array('key1', 'key2'));

Response

return Response::make($contents);
return Response::make($contents, 200);
return Response::json(array('key' => 'value'));
return Response::json(array('key' => 'value'))
->setCallback(Input::get('callback'));
return Response::download($filepath);
return Response::download($filepath, $filename, $headers);
// 創(chuàng)建一個回應(yīng)且修改其頭部信息的值
$response = Response::make($contents, 200);
$response->header('Content-Type', 'application/json');
return $response;
// 為回應(yīng)附加上 cookie
 return Response::make($content)
->withCookie(Cookie::make('key', 'value'));

Container

App::bind('foo', function($app){ return new Foo; });
App::make('foo');
// 如果存在此類, 則返回
 App::make('FooBar');
// 單例模式實例到服務(wù)容器中
 App::singleton('foo', function(){ return new Foo; });
// 將已實例化的對象注冊到服務(wù)容器中
 App::instance('foo', new Foo);
// 注冊綁定規(guī)則到服務(wù)容器中
 App::bind('FooRepositoryInterface', 'BarRepository');
// 給應(yīng)用注冊一個服務(wù)提供者
 App::register('FooServiceProvider');
// 監(jiān)聽容器對某個對象的解析
 App::resolving(function($object){});

Security

哈希

Hash::make('secretpassword');
Hash::check('secretpassword', $hashedPassword);
Hash::needsRehash($hashedPassword);

加密解密

Crypt::encrypt('secretstring');
Crypt::decrypt($encryptedString);
Crypt::setMode('ctr');
Crypt::setCipher($cipher);

Queue

Queue::push('SendMail', array('message' => $message));
Queue::push('SendEmail@send', array('message' => $message));
Queue::push(function($job) use $id {});
// 在多個 workers 中使用相同的負(fù)載
 Queue::bulk(array('SendEmail', 'NotifyUser'), $payload);
// 開啟隊列監(jiān)聽器
php artisan queue:listen
php artisan queue:listen connection
php artisan queue:listen --timeout=60
// 只處理第一個隊列任務(wù)
php artisan queue:work
// 在后臺模式啟動一個隊列 worker
php artisan queue:work --daemon
// 為失敗的任務(wù)創(chuàng)建 migration 文件
php artisan queue:failed-table
// 監(jiān)聽失敗任務(wù)
php artisan queue:failed
// 通過 id 刪除失敗的任務(wù)
php artisan queue:forget 5
// 刪除所有失敗任務(wù)
php artisan queue:flush

Validation

Validator::make(
array('key' => 'Foo'),
array('key' => 'required|in:Foo')
);
Validator::extend('foo', function($attribute, $value, $params){});
Validator::extend('foo', 'FooValidator@validate');
Validator::resolver(function($translator, $data, $rules, $msgs)
{
return new FooValidator($translator, $data, $rules, $msgs);
});

驗證規(guī)則

accepted
active_url
after:YYYY-MM-DD
before:YYYY-MM-DD
alpha
alpha_dash
alpha_num
array
between:1,10
confirmed
date
date_format:YYYY-MM-DD
different:fieldname
digits:value
digits_between:min,max
boolean
email
exists:table,column
image
in:foo,bar,...
not_in:foo,bar,...
integer
numeric
ip
max:value
min:value
mimes:jpeg,png
regex:[0-9]
required
required_if:field,value
required_with:foo,bar,...
required_with_all:foo,bar,...
required_without:foo,bar,...
required_without_all:foo,bar,...
same:field
size:value
timezone
unique:table,column,except,idColumn
url

HTML

HTML::macro('name', function(){});
// 將 HTML 字符串轉(zhuǎn)為實體
HTML::entities($value);
// 將實體轉(zhuǎn)為 HTML 字符
HTML::decode($value);
// 生成 JavaScript 文件鏈接
HTML::script($url, $attributes);
// 生成 CSS 文件鏈接
HTML::style($url, $attributes);
// 生成一個 HTML 圖片元素
HTML::image($url, $alt, $attributes);
// 生成一個 HTML 鏈接
HTML::link($url, 'title', $attributes, $secure);
// 生成一個 HTTPS 類型的 HTML 鏈接
HTML::secureLink($url, 'title', $attributes);
// 給資源文件生成一個 HTML link
HTML::linkAsset($url, 'title', $attributes, $secure);
// 給資源文件生成一個 HTTPS HTML 鏈接
HTML::linkSecureAsset($url, 'title', $attributes);
// 給命名路由生成一個 HTML 鏈接
HTML::linkRoute($name, 'title', $parameters, $attributes);
// 給控制器動作生成 HTML 鏈接
HTML::linkAction($action, 'title', $parameters, $attributes);
// 給郵件地址生成 HTML 鏈接
HTML::mailto($email, 'title', $attributes);
// 混淆一個郵件地址以阻止垃圾郵件掃描器的嗅探
HTML::email($email);
// 生成有序列表
HTML::ol($list, $attributes);
// 生成無序列表
HTML::ul($list, $attributes);
HTML::listing($type, $list, $attributes);
HTML::listingElement($key, $type, $value);
HTML::nestedListing($key, $type, $value);
// 從數(shù)組中構(gòu)建 HTML 屬性
HTML::attributes($attributes);
// 構(gòu)建單屬性元素
HTML::attributeElement($key, $value);
// 混淆一個字符串以阻止垃圾郵件掃描器的嗅探
HTML::obfuscate($value);

Config

Config::get('app.timezone');
//指定默認(rèn)值
 Config::get('app.timezone', 'UTC');
Config::set('database.default', 'sqlite');

Route

Route::get('foo', function(){});
Route::get('foo', 'ControllerName@function');
Route::controller('foo', 'FooController');

資源路由?

Route::resource('posts','PostsController');
// 資源路由器只允許指定動作通過
 Route::resource('photo', 'PhotoController',['only' => ['index', 'show']]);
Route::resource('photo', 'PhotoController',['except' => ['update', 'destroy']]);

觸發(fā)錯誤?

App::abort(404);
$handler->missing(...) in ErrorServiceProvider::boot();
throw new NotFoundHttpException;

路由參數(shù)?

Route::get('foo/{bar}', function($bar){});
Route::get('foo/{bar?}', function($bar = 'bar'){});

HTTP 請求方式

Route::any('foo', function(){});
Route::post('foo', function(){});
Route::put('foo', function(){});
Route::patch('foo', function(){});
Route::delete('foo', function(){});
// RESTful 資源控制器
 Route::resource('foo', 'FooController');
// 為一個路由注冊多種請求方式
 Route::match(['get', 'post'], '/', function(){});

安全路由 (TBD)

Route::get('foo', array('https', function(){}));

路由約束

Route::get('foo/{bar}', function($bar){})
->where('bar', '[0-9]+');
Route::get('foo/{bar}/{baz}', function($bar, $baz){})
->where(array('bar' => '[0-9]+', 'baz' => '[A-Za-z]'))

// 設(shè)置一個可跨路由使用的模式
 Route::pattern('bar', '[0-9]+')

HTTP 中間件?

// 為路由指定 Middleware
 Route::get('admin/profile', ['middleware' => 'auth', function(){}]);
Route::get('admin/profile', function(){})->middleware('auth');

命名路由

Route::currentRouteName();
Route::get('foo/bar', array('as' => 'foobar', function(){}));
Route::get('user/profile', [
'as' => 'profile', 'uses' => 'UserController@showProfile'
]);
Route::get('user/profile', 'UserController@showProfile')->name('profile');
$url = route('profile');
$redirect = redirect()->route('profile');

路由前綴

Route::group(['prefix' => 'admin'], function()
{
Route::get('users', function(){
return 'Matches The "/admin/users" URL';
});
});

路由命名空間

// 此路由組將會傳送 'Foo\Bar' 命名空間
 Route::group(array('namespace' => 'Foo\Bar'), function(){})

子域名路由

// {sub} 將在閉包中被忽略
 Route::group(array('domain' => '{sub}.example.com'), function(){});

Model

基礎(chǔ)使用?

// 定義一個 Eloquent 模型
 class User extends Model {}
// 生成一個 Eloquent 模型
php artisan make:model User
// 指定一個自定義的數(shù)據(jù)表名稱
 class User extends Model {
  protected $table = 'my_users';
}

More

Model::create(array('key' => 'value'));
// 通過屬性找到第一條相匹配的數(shù)據(jù)或創(chuàng)造一條新數(shù)據(jù)
 Model::firstOrCreate(array('key' => 'value'));
// 通過屬性找到第一條相匹配的數(shù)據(jù)或?qū)嵗粭l新數(shù)據(jù)
 Model::firstOrNew(array('key' => 'value'));
// 通過屬性找到相匹配的數(shù)據(jù)并更新,如果不存在即創(chuàng)建
 Model::updateOrCreate(array('search_key' => 'search_value'), array('key' => 'value'));
// 使用屬性的數(shù)組來填充一個模型, 用的時候要小心「Mass Assignment」安全問題 !
 Model::fill($attributes);
Model::destroy(1);
Model::all();
Model::find(1);
// 使用雙主鍵進(jìn)行查找
 Model::find(array('first', 'last'));
// 查找失敗時拋出異常
 Model::findOrFail(1);
// 使用雙主鍵進(jìn)行查找, 失敗時拋出異常
 Model::findOrFail(array('first', 'last'));
Model::where('foo', '=', 'bar')->get();
Model::where('foo', '=', 'bar')->first();
Model::where('foo', '=', 'bar')->exists();
// 動態(tài)屬性查找
 Model::whereFoo('bar')->first();
// 查找失敗時拋出異常
 Model::where('foo', '=', 'bar')->firstOrFail();
Model::where('foo', '=', 'bar')->count();
Model::where('foo', '=', 'bar')->delete();
// 輸出原始的查詢語句
 Model::where('foo', '=', 'bar')->toSql();
Model::whereRaw('foo = bar and cars = 2', array(20))->get();
Model::on('connection-name')->find(1);
Model::with('relation')->get();
Model::all()->take(10);
Model::all()->skip(10);
// 默認(rèn)的 Eloquent 排序是上升排序
 Model::all()->orderBy('column');
Model::all()->orderBy('column','desc');

軟刪除?

Model::withTrashed()->where('cars', 2)->get();
// 在查詢結(jié)果中包括帶被軟刪除的模型
 Model::withTrashed()->where('cars', 2)->restore();
Model::where('cars', 2)->forceDelete();
// 查找只帶有軟刪除的模型
 Model::onlyTrashed()->where('cars', 2)->get();

模型關(guān)聯(lián)

// 一對一 - User::phone()
 return $this->hasOne('App\Phone', 'foreign_key', 'local_key');
// 一對一 - Phone::user(), 定義相對的關(guān)聯(lián)
 return $this->belongsTo('App\User', 'foreign_key', 'other_key');

// 一對多 - Post::comments()
 return $this->hasMany('App\Comment', 'foreign_key', 'local_key');
//  一對多 - Comment::post()
 return $this->belongsTo('App\Post', 'foreign_key', 'other_key');

// 多對多 - User::roles();
 return $this->belongsToMany('App\Role', 'user_roles', 'user_id', 'role_id');
// 多對多 - Role::users();
 return $this->belongsToMany('App\User');
// 多對多 - Retrieving Intermediate Table Columns
$role->pivot->created_at;
// 多對多 - 中介表字段
 return $this->belongsToMany('App\Role')->withPivot('column1', 'column2');
// 多對多 - 自動維護(hù) created_at 和 updated_at 時間戳
 return $this->belongsToMany('App\Role')->withTimestamps();

// 遠(yuǎn)層一對多 - Country::posts(), 一個 Country 模型可能通過中介的 Users
 // 模型關(guān)聯(lián)到多個 Posts 模型(User::country_id)
 return $this->hasManyThrough('App\Post', 'App\User', 'country_id', 'user_id');

// 多態(tài)關(guān)聯(lián) - Photo::imageable()
 return $this->morphTo();
// 多態(tài)關(guān)聯(lián) - Staff::photos()
 return $this->morphMany('App\Photo', 'imageable');
// 多態(tài)關(guān)聯(lián) - Product::photos()
 return $this->morphMany('App\Photo', 'imageable');
// 多態(tài)關(guān)聯(lián) - 在 AppServiceProvider 中注冊你的「多態(tài)對照表」
 Relation::morphMap([
    'Post' => App\Post::class,
    'Comment' => App\Comment::class,
]);

// 多態(tài)多對多關(guān)聯(lián) - 涉及數(shù)據(jù)庫表: posts,videos,tags,taggables
 // Post::tags()
 return $this->morphToMany('App\Tag', 'taggable');
// Video::tags()
 return $this->morphToMany('App\Tag', 'taggable');
// Tag::posts()
 return $this->morphedByMany('App\Post', 'taggable');
// Tag::videos()
 return $this->morphedByMany('App\Video', 'taggable');

// 查找關(guān)聯(lián)
$user->posts()->where('active', 1)->get();
// 獲取所有至少有一篇評論的文章...
$posts = App\Post::has('comments')->get();
// 獲取所有至少有三篇評論的文章...
$posts = Post::has('comments', '>=', 3)->get();
// 獲取所有至少有一篇評論被評分的文章...
$posts = Post::has('comments.votes')->get();
// 獲取所有至少有一篇評論相似于 foo% 的文章
$posts = Post::whereHas('comments', function ($query) {
    $query->where('content', 'like', 'foo%');
})->get();

// 預(yù)加載
$books = App\Book::with('author')->get();
$books = App\Book::with('author', 'publisher')->get();
$books = App\Book::with('author.contacts')->get();

// 延遲預(yù)加載
$books->load('author', 'publisher');

// 寫入關(guān)聯(lián)模型
$comment = new App\Comment(['message' => 'A new comment.']);
$post->comments()->save($comment);
// Save 與多對多關(guān)聯(lián)
$post->comments()->saveMany([
    new App\Comment(['message' => 'A new comment.']),
    new App\Comment(['message' => 'Another comment.']),
]);
$post->comments()->create(['message' => 'A new comment.']);

// 更新「從屬」關(guān)聯(lián)
$user->account()->associate($account);
$user->save();
$user->account()->dissociate();
$user->save();

// 附加多對多關(guān)系
$user->roles()->attach($roleId);
$user->roles()->attach($roleId, ['expires' => $expires]);
// 從用戶上移除單一身份...
$user->roles()->detach($roleId);
// 從用戶上移除所有身份...
$user->roles()->detach();
$user->roles()->detach([1, 2, 3]);
$user->roles()->attach([1 => ['expires' => $expires], 2, 3]);

// 任何不在給定數(shù)組中的 IDs 將會從中介表中被刪除。
$user->roles()->sync([1, 2, 3]);
// 你也可以傳遞中介表上該 IDs 額外的值:
$user->roles()->sync([1 => ['expires' => true], 2, 3]);

事件

Model::creating(function($model){});
Model::created(function($model){});
Model::updating(function($model){});
Model::updated(function($model){});
Model::saving(function($model){});
Model::saved(function($model){});
Model::deleting(function($model){});
Model::deleted(function($model){});
Model::observe(new FooObserver);

Eloquent 配置信息

// 關(guān)閉模型插入或更新操作引發(fā)的 「mass assignment」異常
 Eloquent::unguard();
// 重新開啟「mass assignment」異常拋出功能
 Eloquent::reguard();

Cache

Cache::put('key', 'value', $minutes);
Cache::add('key', 'value', $minutes);
Cache::forever('key', 'value');
Cache::remember('key', $minutes, function(){ return 'value' });
Cache::rememberForever('key', function(){ return 'value' });
Cache::forget('key');
Cache::has('key');
Cache::get('key');
Cache::get('key', 'default');
Cache::get('key', function(){ return 'default'; });
Cache::tags('my-tag')->put('key','value', $minutes);
Cache::tags('my-tag')->has('key');
Cache::tags('my-tag')->get('key');
Cache::tags('my-tag')->forget('key');
Cache::tags('my-tag')->flush();
Cache::increment('key');
Cache::increment('key', $amount);
Cache::decrement('key');
Cache::decrement('key', $amount);
Cache::section('group')->put('key', $value);
Cache::section('group')->get('key');
Cache::section('group')->flush();

Cookie

Cookie::get('key');
Cookie::get('key', 'default');
// 創(chuàng)建一個永久有效的 cookie
 Cookie::forever('key', 'value');
// 創(chuàng)建一個 N 分鐘有效的 cookie
 Cookie::make('key', 'value', 'minutes');
// 在回應(yīng)之前先積累 cookie,回應(yīng)時統(tǒng)一返回
 Cookie::queue('key', 'value', 'minutes');
// 移除 Cookie
 Cookie::forget('key');
// 從 response 發(fā)送一個 cookie
$response = Response::make('Hello World');
$response->withCookie(Cookie::make('name', 'value', $minutes));

Request

// url: http://xx.com/aa/bb
 Request::url();
// 路徑: /aa/bb
 Request::path();
// 獲取請求 Uri: /aa/bb/?c=d
 Request::getRequestUri();
// 返回用戶的 IP
 Request::ip();
// 獲取 Uri: http://xx.com/aa/bb/?c=d
 Request::getUri();
// 獲取查詢字符串: c=d
 Request::getQueryString();
// 獲取請求端口 (例如 80, 443 等等)
 Request::getPort();
// 判斷當(dāng)前請求的 URI 是否可被匹配
 Request::is('foo/*');
// 獲取 URI 的分段值 (索引從 1 開始)
 Request::segment(1);
// 從請求中取回頭部信息
 Request::header('Content-Type');
// 從請求中取回服務(wù)器變量
 Request::server('PATH_INFO');
// 判斷請求是否是 AJAX 請求
 Request::ajax();
// 判斷請求是否使用 HTTPS
 Request::secure();
// 獲取請求方法
 Request::method();
// 判斷請求方法是否是指定類型的
 Request::isMethod('post');
// 獲取原始的 POST 數(shù)據(jù)
 Request::instance()->getContent();
// 獲取請求要求返回的格式
 Request::format();
// 判斷 HTTP Content-Type 頭部信息是否包含 */json
 Request::isJson();
// 判斷 HTTP Accept 頭部信息是否為 application/json
 Request::wantsJson();

Redirect

return Redirect::to('foo/bar');
return Redirect::to('foo/bar')->with('key', 'value');
return Redirect::to('foo/bar')->withInput(Input::get());
return Redirect::to('foo/bar')->withInput(Input::except('password'));
return Redirect::to('foo/bar')->withErrors($validator);
// 重定向到之前的請求
 return Redirect::back();
// 重定向到命名路由(根據(jù)命名路由算出 URL)
 return Redirect::route('foobar');
return Redirect::route('foobar', array('value'));
return Redirect::route('foobar', array('key' => 'value'));
// 重定向到控制器動作(根據(jù)控制器動作算出 URL)
 return Redirect::action('FooController@index');
return Redirect::action('FooController@baz', array('value'));
return Redirect::action('FooController@baz', array('key' => 'value'));
// 跳轉(zhuǎn)到目的地址,如果沒有設(shè)置則使用默認(rèn)值 foo/bar
 return Redirect::intended('foo/bar');

Mail

Mail::send('email.view', $data, function($message){});
Mail::send(array('html.view', 'text.view'), $data, $callback);
Mail::queue('email.view', $data, function($message){});
Mail::queueOn('queue-name', 'email.view', $data, $callback);
Mail::later(5, 'email.view', $data, function($message){});
// 零時將發(fā)送郵件請求寫入 log,方便測試
 Mail::pretend();

消息

// 這些都能在 $message 實例中使用, 并可傳入到 Mail::send() 或 Mail::queue()
$message->from('email@example.com', 'Mr. Example');
$message->sender('email@example.com', 'Mr. Example');
$message->returnPath('email@example.com');
$message->to('email@example.com', 'Mr. Example');
$message->cc('email@example.com', 'Mr. Example');
$message->bcc('email@example.com', 'Mr. Example');
$message->replyTo('email@example.com', 'Mr. Example');
$message->subject('Welcome to the Jungle');
$message->priority(2);
$message->attach('foo\bar.txt', $options);
// 使用內(nèi)存數(shù)據(jù)作為附件
$message->attachData('bar', 'Data Name', $options);
// 附帶文件,并返回 CID
$message->embed('foo\bar.txt');
$message->embedData('foo', 'Data Name', $options);
// 獲取底層的 Swift Message 對象
$message->getSwiftMessage();

View

View::make('path/to/view');
View::make('foo/bar')->with('key', 'value');
View::make('foo/bar')->withKey('value');
View::make('foo/bar', array('key' => 'value'));
View::exists('foo/bar');
// 跨視圖共享變量
 View::share('key', 'value');
// 視圖嵌套
 View::make('foo/bar')->nest('name', 'foo/baz', $data);
// 注冊一個視圖構(gòu)造器
 View::composer('viewname', function($view){});
// 注冊多個視圖到一個視圖構(gòu)造器中
 View::composer(array('view1', 'view2'), function($view){});
// 注冊一個視圖構(gòu)造器類
 View::composer('viewname', 'FooComposer');
View::creator('viewname', function($view){});

Blade

// 區(qū)塊占位
 @yield('name')
// 擴(kuò)展布局模板
 @extends('layout.name')
// 實現(xiàn)命名為 name 的區(qū)塊(yield 占位的地方)
 @section('name')
@stop
// 可繼承內(nèi)容區(qū)塊
 @section('sidebar')
@show
// 繼承父模板內(nèi)容(@show 的區(qū)塊內(nèi)容)
 @parent
// 包含子視圖
 @include('view.name')
// 包含子視圖,并傳參
 @include('view.name', array('key' => 'value'));
// 加載本地化語句
 @lang('messages.name')
@choice('messages.name', 1);

@if
@else
@elseif
@endif

@unless
@endunless

@for
@endfor

@foreach
@endforeach

@while
@endwhile

//forelse 4.2 feature
 @forelse($users as $user)
@empty
@endforelse

// 輸出內(nèi)容,被轉(zhuǎn)義過的
 {{ $var }}
// 輸出未轉(zhuǎn)義內(nèi)容,5.0 特性
 {!! $var !!}
{{-- Blade 注釋,不會被輸出到頁面中 --}}
// 三元表達(dá)式的簡寫,以下相當(dāng)于「$name ? $name : 'Default'」
 {{{ $name or 'Default' }}}
// 保留雙大括號,以下會編譯為 {{ name }}
 @{{ name }}

String

// 將 UTF-8 的值直譯為 ASCII 類型的值
 Str::ascii($value)
Str::camel($value)
Str::contains($haystack, $needle)
Str::endsWith($haystack, $needles)
Str::finish($value, $cap)
Str::is($pattern, $value)
Str::length($value)
Str::limit($value, $limit = 100, $end = '...')
Str::lower($value)
Str::words($value, $words = 100, $end = '...')
Str::plural($value, $count = 2)
// 生成更加真實的 "隨機(jī)" 字母數(shù)字字符串.
 Str::random($length = 16)
// 生成一個 "隨機(jī)" 字母數(shù)字字符串.
 Str::quickRandom($length = 16)
Str::upper($value)
Str::title($value)
Str::singular($value)
Str::slug($title, $separator = '-')
Str::snake($value, $delimiter = '_')
Str::startsWith($haystack, $needles)
Str::studly($value)
Str::macro($name, $macro)

Collection

// 創(chuàng)建集合
collect([1, 2, 3]);
// 返回該集合所代表的底層數(shù)組:
$collection->all();
// 返回集合中所有項目的平均值:
$collection->avg();
// 將集合拆成多個給定大小的較小集合:
$collection->chunk(4);
// 將多個數(shù)組組成的集合折成單一數(shù)組集合:
$collection->collapse();
// 用來判斷該集合是否含有指定的項目:
$collection->contains('New York');
// 返回該集合內(nèi)的項目總數(shù):
$collection->count();
// 遍歷集合中的項目,并將之傳入給定的回調(diào)函數(shù):
$collection = $collection->each(function ($item, $key) {
});
// 會創(chuàng)建一個包含第 n 個元素的新集合:
$collection->every(4);
// 傳遞偏移值作為第二個參數(shù):
$collection->every(4, 1);
// 返回集合中排除指定鍵的所有項目:
$collection->except(['price', 'discount']);
// 以給定的回調(diào)函數(shù)篩選集合,只留下那些通過判斷測試的項目:
$filtered = $collection->filter(function ($item) {
    return $item > 2;
});
// 返回集合中,第一個通過給定測試的元素:
collect([1, 2, 3, 4])->first(function ($key, $value) {
    return $value > 2;
});
// 將多維集合轉(zhuǎn)為一維集合:
$flattened = $collection->flatten();
// 將集合中的鍵和對應(yīng)的數(shù)值進(jìn)行互換:
$flipped = $collection->flip();
// 以鍵自集合移除掉一個項目:
$collection->forget('name');
// 返回含有可以用來在給定頁碼顯示項目的新集合:
$chunk = $collection->forPage(2, 3);
// 返回給定鍵的項目。如果該鍵不存在,則返回 null:
$value = $collection->get('name');
// 根據(jù)給定的鍵替集合內(nèi)的項目分組:
$grouped = $collection->groupBy('account_id');
// 用來確認(rèn)集合中是否含有給定的鍵:
$collection->has('email');
// 用來連接集合中的項目
$collection->implode('product', ', ');
// 移除任何給定數(shù)組或集合內(nèi)所沒有的數(shù)值:
$intersect = $collection->intersect(['Desk', 'Chair', 'Bookcase']);
// 假如集合是空的,isEmpty 方法會返回 true:
collect([])->isEmpty();
// 以給定鍵的值作為集合項目的鍵:
$keyed = $collection->keyBy('product_id');
// 傳入回調(diào)函數(shù),該函數(shù)會返回集合的鍵的值:
$keyed = $collection->keyBy(function ($item) {
    return strtoupper($item['product_id']);
});
// 返回該集合所有的鍵:
$keys = $collection->keys();
// 返回集合中,最后一個通過給定測試的元素:
$collection->last();
// 遍歷整個集合并將每一個數(shù)值傳入給定的回調(diào)函數(shù):
$multiplied = $collection->map(function ($item, $key) {
    return $item * 2;
});
// 返回給定鍵的最大值:
$max = collect([['foo' => 10], ['foo' => 20]])->max('foo');
$max = collect([1, 2, 3, 4, 5])->max();
// 將給定的數(shù)組合并進(jìn)集合:
$merged = $collection->merge(['price' => 100, 'discount' => false]);
// 返回給定鍵的最小值:
$min = collect([['foo' => 10], ['foo' => 20]])->min('foo');
$min = collect([1, 2, 3, 4, 5])->min();
// 返回集合中指定鍵的所有項目:
$filtered = $collection->only(['product_id', 'name']);
// 獲取所有集合中給定鍵的值:
$plucked = $collection->pluck('name');
// 移除并返回集合最后一個項目:
$collection->pop();
// 在集合前面增加一個項目:
$collection->prepend(0);
// 傳遞第二個參數(shù)來設(shè)置前置項目的鍵:
$collection->prepend(0, 'zero');
// 以鍵從集合中移除并返回一個項目:
$collection->pull('name');
// 附加一個項目到集合后面:
$collection->push(5);
// put 在集合內(nèi)設(shè)置一個給定鍵和數(shù)值:
$collection->put('price', 100);
// 從集合中隨機(jī)返回一個項目:
$collection->random();
// 傳入一個整數(shù)到 random。如果該整數(shù)大于 1,則會返回一個集合:
$random = $collection->random(3);
// 會將每次迭代的結(jié)果傳入到下一次迭代:
$total = $collection->reduce(function ($carry, $item) {
    return $carry + $item;
});
// 以給定的回調(diào)函數(shù)篩選集合:
$filtered = $collection->reject(function ($item) {
    return $item > 2;
});
// 反轉(zhuǎn)集合內(nèi)項目的順序:
$reversed = $collection->reverse();
// 在集合內(nèi)搜索給定的數(shù)值并返回找到的鍵:
$collection->search(4);
// 移除并返回集合的第一個項目:
$collection->shift();
// 隨機(jī)排序集合的項目:
$shuffled = $collection->shuffle();
// 返回集合從給定索引開始的一部分切片:
$slice = $collection->slice(4);
// 對集合排序:
$sorted = $collection->sort();
// 以給定的鍵排序集合:
$sorted = $collection->sortBy('price');
// 移除并返回從指定的索引開始的一小切片項目:
$chunk = $collection->splice(2);
// 返回集合內(nèi)所有項目的總和:
collect([1, 2, 3, 4, 5])->sum();
// 返回有著指定數(shù)量項目的集合:
$chunk = $collection->take(3);
// 將集合轉(zhuǎn)換成純 PHP 數(shù)組:
$collection->toArray();
// 將集合轉(zhuǎn)換成 JSON:
$collection->toJson();
// 遍歷集合并對集合內(nèi)每一個項目調(diào)用給定的回調(diào)函數(shù):
$collection->transform(function ($item, $key) {
    return $item * 2;
});
// 返回集合中所有唯一的項目:
$unique = $collection->unique();
// 返回鍵重設(shè)為連續(xù)整數(shù)的的新集合:
$values = $collection->values();
// 以一對給定的鍵/數(shù)值篩選集合:
$filtered = $collection->where('price', 100);
// 將集合與給定數(shù)組同樣索引的值合并在一起:
$zipped = $collection->zip([100, 200]);