1. 程式人生 > 其它 >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
// 強制輸出 ANSI 格式
php artisan --ansi
// 禁止輸出 ANSI 格式
php artisan --no-ansi
// 顯示當前命令列執行的環境
php artisan --env
// -v|vv|vvv 通過增加 v 的個數來控制命令列輸出內容的詳盡情況: 1 個代表正常輸出, 2 個代表輸出更多訊息, 3 個代表除錯
php artisan --verbose
// 移除編譯優化過的檔案 (storage/frameworks/compiled.php)
php artisan clear-compiled
// 顯示當前框架執行的環境
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]
// 啟動內建伺服器
php artisan serve
// 更改預設埠
php artisan serve --port 8080
// 使其在本地伺服器外也可正常工作
php artisan serve --host 0.0.0.0
// 更改應用名稱空間
php artisan app:name namespace
// 清除過期的密碼重置令牌
php artisan auth:clear-resets
// 清空應用快取
php artisan cache:clear
// 建立快取資料庫表 migration
php artisan cache:table
// 合併所有的配置資訊為一個,提高載入速度
php artisan config:cache
// 移除配置快取檔案
php artisan config:clear
// 程式內部呼叫 Artisan 命令
$exitCode = Artisan::call('config:cache');
// 執行所有的 seed 假資料生成類
// --class      可以指定執行的類,預設是: "DatabaseSeeder"
// --database   可以指定資料庫
// --force      當處於生產環境時強制執行操作
php artisan db:seed [--class[="..."]] [--database[="..."]] [--force]

// 基於註冊的資訊,生成遺漏的 events 和 handlers
php artisan event:generate

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

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

// 在預設情況下, 這將建立未加入佇列的自處理命令
// 通過 --handler 標識來生成一個處理器, 用 --queued 來使其入佇列.
php artisan make:command [--handler] [--queued] name
// 建立一個新的 Artisan 命令
//  --command     命令被呼叫的名稱。 (預設為: "command:name")
php artisan make:console [--command[="..."]] name
// 建立一個新的資源控制器
// --plain      生成一個空白的控制器類
php artisan make:controller [--plain] name
php artisan make:controller App\\Admin\\Http\\Controllers\\DashboardController
// 建立一個新的事件類
php artisan make:event name
// 建立一個新的中介軟體類
php artisan make:middleware name
// 建立一個新的遷移檔案
// --create     將被建立的資料表.
// --table      將被遷移的資料表.
php artisan make:migration [--create[="..."]] [--table[="..."]] name
// 建立一個新的 Eloquent 模型類
php artisan make:model name
// 建立一個新的服務提供者類
php artisan make:provider name
// 建立一個新的表單請求類
php artisan make:request name
// 資料庫遷移
// --database   指定資料庫連線(下同)
// --force      當處於生產環境時強制執行,不詢問(下同)
// --path       指定單獨遷移檔案地址
// --pretend    把將要執行的 SQL 語句打印出來(下同)
// --seed       Seed 任務是否需要被重新執行(下同)
php artisan migrate [--database[="..."]] [--force] [--path[="..."]] [--pretend] [--seed]
// 建立遷移資料庫表
php artisan migrate:install [--database[="..."]]
// 重置並重新執行所有的 migrations
// --seeder     指定主 Seeder 的類名
php artisan migrate:refresh [--database[="..."]] [--force] [--seed] [--seeder[="..."]]
// 回滾所有的資料庫遷移
php artisan migrate:reset [--database[="..."]] [--force] [--pretend]
// 回滾最最近一次執行的遷移任務
php artisan migrate:rollback [--database[="..."]] [--force] [--pretend]
// migrations 資料庫表資訊
php artisan migrate:status
// 為佇列資料庫表建立一個新的遷移
php artisan queue:table
// 監聽指定的佇列
// --queue      被監聽的佇列
// --delay      給執行失敗的任務設定延時時間 (預設為零: 0)
// --memory     記憶體限制大小,單位為 MB (預設為: 128)
// --timeout    指定任務執行超時秒數 (預設為: 60)
// --sleep      等待檢查佇列任務的秒數 (預設為: 3)
// --tries      任務記錄失敗重試次數 (預設為: 0)
php artisan queue:listen [--queue[="..."]] [--delay[="..."]] [--memory[="..."]] [--timeout[="..."]] [--sleep[="..."]] [--tries[="..."]] [connection]
// 檢視所有執行失敗的佇列任務
php artisan queue:failed
// 為執行失敗的資料表任務建立一個遷移
php artisan queue:failed-table
// 清除所有執行失敗的佇列任務
php artisan queue:flush
// 刪除一個執行失敗的佇列任務
php artisan queue:forget
// 在當前的佇列任務執行完畢後, 重啟佇列的守護程序
php artisan queue:restart
// 對指定 id 的執行失敗的佇列任務進行重試(id: 失敗佇列任務的 ID)
php artisan queue:retry id
// 指定訂閱 Iron.io 佇列的連結
// queue: Iron.io 的佇列名稱.
// url: 將被訂閱的 URL.
// --type       指定佇列的推送型別.
php artisan queue:subscribe [--type[="..."]] queue url
// 處理下一個佇列任務
// --queue      被監聽的佇列
// --daemon     在後臺模式執行
// --delay      給執行失敗的任務設定延時時間 (預設為零: 0)
// --force      強制在「維護模式下」執行
// --memory     記憶體限制大小,單位為 MB (預設為: 128)
// --sleep      當沒有任務處於有效狀態時, 設定其進入休眠的秒數 (預設為: 3)
// --tries      任務記錄失敗重試次數 (預設為: 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 資料表生成遷移檔案
php artisan session:table

// 從 vendor 的擴充套件包中釋出任何可釋出的資源
// --force        重寫所有已存在的檔案
// --provider     指定你想要釋出資原始檔的服務提供者
// --tag          指定你想要釋出標記資源.
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);
// 在頁面列印分頁導航欄
$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');
// 獲取檔案內容
File::getRequire('path');
// 獲取檔案內容, 僅能引入一次
File::requireOnce('path');
// 將內容寫入檔案
File::put('path', 'contents');
// 將內容新增在檔案原內容後
File::append('path', 'data');
// 通過給定的路徑來刪除檔案
File::delete('path');
// 將檔案移動到新目錄下
File::move('path', 'target');
// Copy a file to a new location
// 將檔案複製到新目錄下
File::copy('path', 'target');
// 從檔案的路徑地址提取檔案的擴充套件
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.
// 獲取一個目錄下的所有檔案, 以陣列型別返回
File::files('directory');
// 獲取一個目錄下的所有檔案 (遞迴).
File::allFiles('directory');
// 獲取一個目錄內的目錄
File::directories('directory');
// 建立一個目錄
File::makeDirectory('path',  $mode = 0777, $recursive = false);
// 將資料夾從一個目錄複製到另一個目錄下
File::copyDirectory('directory', 'destination', $options = null);
// 遞迴式刪除目錄
File::deleteDirectory('directory', $preserve = false);
// 清空指定目錄的所有檔案和資料夾
File::cleanDirectory('directory');

  

SSH

Executing Commands
SSH::run(array $commands);
// 指定 remote, 否則將使用預設值
SSH::into($remote)->run(array $commands);
SSH::run(array $commands, function($line)
{
  echo $line.PHP_EOL;
});
              
任務
// 定義任務
SSH::define($taskName, array $commands);
// 執行任務
SSH::task($taskName, function($line)
{
  echo $line.PHP_EOL;
});
              
SFTP 上傳
SSH::put($localFile, $remotePath);
SSH::putString($string, $remotePath);

  

Schema

// 建立指定資料表
Schema::create('table', function($table)
{
  $table->increments('id');
});
// 指定一個連線
Schema::connection('foo')->create('table', function($table){});
// 通過給定的名稱來重新命名資料表
Schema::rename($from, $to);
// 移除指定資料表
Schema::drop('table');
// 當資料表存在時, 將指定資料表移除
Schema::dropIfExists('table');
// 判斷資料表是否存在
Schema::hasTable('table');
// 判斷資料表是否有該列
Schema::hasColumn('table', 'column');
// 更新一個已存在的資料表
Schema::table('table', function($table){});
// 重新命名資料表的列
$table->renameColumn('from', 'to');
// 移除指定的資料表列
$table->dropColumn(string|array);
// 指定資料表使用的儲存引擎
$table->engine = 'InnoDB';
// 欄位順序,只能在 MySQL 中才能用
$table->string('name')->after('email');
              
索引
$table->string('column')->unique();
$table->primary('column');
// 建立一個雙主鍵
$table->primary(array('first', 'last'));
$table->unique('column');
$table->unique('column', 'key_name');
// 建立一個雙唯一性索引
$table->unique(array('first', 'last'));
$table->unique(array('first', 'last'), 'key_name');
$table->index('column');
$table->index('column', 'key_name');
// 建立一個雙索引
$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');

// 數字
$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()

  

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 中使用相同的負載
Queue::bulk(array('SendEmail', 'NotifyUser'), $payload);
// 開啟佇列監聽器
php artisan queue:listen
php artisan queue:listen connection
php artisan queue:listen --timeout=60
// 只處理第一個佇列任務
php artisan queue:work
// 在後臺模式啟動一個佇列 worker
php artisan queue:work --daemon
// 為失敗的任務建立 migration 檔案
php artisan queue:failed-table
// 監聽失敗任務
php artisan queue:failed
// 通過 id 刪除失敗的任務
php artisan queue:forget 5
// 刪除所有失敗任務
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);
});
              
Rules
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 字串轉為實體
HTML::entities($value);
// 將實體轉為 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);
// 從陣列中構建 HTML 屬性
HTML::attributes($attributes);
// 構建單屬性元素
HTML::attributeElement($key, $value);
// 混淆一個字串以阻止垃圾郵件掃描器的嗅探
HTML::obfuscate($value);

  

Collection

// 建立集合
collect([1, 2, 3]);
// 返回該集合所代表的底層陣列:
$collection->all();
// 返回集合中所有專案的平均值:
$collection->avg();
// 將集合拆成多個給定大小的較小集合:
$collection->chunk(4);
// 將多個數組組成的集合折成單一陣列集合:
$collection->collapse();
// 用來判斷該集合是否含有指定的專案:
$collection->contains('New York');
// 返回該集合內的專案總數:
$collection->count();
// 遍歷集合中的專案,並將之傳入給定的回撥函式:
$collection = $collection->each(function ($item, $key) {
});
// 會建立一個包含第 n 個元素的新集合:
$collection->every(4);
// 傳遞偏移值作為第二個引數:
$collection->every(4, 1);
// 返回集合中排除指定鍵的所有專案:
$collection->except(['price', 'discount']);
// 以給定的回撥函式篩選集合,只留下那些通過判斷測試的專案:
$filtered = $collection->filter(function ($item) {
    return $item > 2;
});
// 返回集合中,第一個通過給定測試的元素:
collect([1, 2, 3, 4])->first(function ($key, $value) {
    return $value > 2;
});
// 將多維集合轉為一維集合:
$flattened = $collection->flatten();
// 將集合中的鍵和對應的數值進行互換:
$flipped = $collection->flip();
// 以鍵自集合移除掉一個專案:
$collection->forget('name');
// 返回含有可以用來在給定頁碼顯示專案的新集合:
$chunk = $collection->forPage(2, 3);
// 返回給定鍵的專案。如果該鍵不存在,則返回 null:
$value = $collection->get('name');
// 根據給定的鍵替集合內的專案分組:
$grouped = $collection->groupBy('account_id');
// 用來確認集合中是否含有給定的鍵:
$collection->has('email');
// 用來連線集合中的專案
$collection->implode('product', ', ');
// 移除任何給定陣列或集合內所沒有的數值:
$intersect = $collection->intersect(['Desk', 'Chair', 'Bookcase']);
// 假如集合是空的,isEmpty 方法會返回 true:
collect([])->isEmpty();
// 以給定鍵的值作為集合專案的鍵:
$keyed = $collection->keyBy('product_id');
// 傳入回撥函式,該函式會返回集合的鍵的值:
$keyed = $collection->keyBy(function ($item) {
    return strtoupper($item['product_id']);
});
// 返回該集合所有的鍵:
$keys = $collection->keys();
// 返回集合中,最後一個通過給定測試的元素:
$collection->last();
// 遍歷整個集合並將每一個數值傳入給定的回撥函式:
$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();
// 將給定的數組合並進集合:
$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);
// 傳遞第二個引數來設定前置專案的鍵:
$collection->prepend(0, 'zero');
// 以鍵從集合中移除並返回一個專案:
$collection->pull('name');
// 附加一個專案到集合後面:
$collection->push(5);
// put 在集合內設定一個給定鍵和數值:
$collection->put('price', 100);
// 從集合中隨機返回一個專案:
$collection->random();
// 傳入一個整數到 random。如果該整數大於 1,則會返回一個集合:
$random = $collection->random(3);
// 會將每次迭代的結果傳入到下一次迭代:
$total = $collection->reduce(function ($carry, $item) {
    return $carry + $item;
});
// 以給定的回撥函式篩選集合:
$filtered = $collection->reject(function ($item) {
    return $item > 2;
});
// 反轉集合內專案的順序:
$reversed = $collection->reverse();
// 在集合內搜尋給定的數值並返回找到的鍵:
$collection->search(4);
// 移除並返回集合的第一個專案:
$collection->shift();
// 隨機排序集合的專案:
$shuffled = $collection->shuffle();
// 返回集合從給定索引開始的一部分切片:
$slice = $collection->slice(4);
// 對集合排序:
$sorted = $collection->sort();
// 以給定的鍵排序集合:
$sorted = $collection->sortBy('price');
// 移除並返回從指定的索引開始的一小切片專案:
$chunk = $collection->splice(2);
// 返回集合內所有專案的總和:
collect([1, 2, 3, 4, 5])->sum();
// 返回有著指定數量專案的集合:
$chunk = $collection->take(3);
// 將集合轉換成純 PHP 陣列:
$collection->toArray();
// 將集合轉換成 JSON:
$collection->toJson();
// 遍歷集合並對集合內每一個專案呼叫給定的回撥函式:
$collection->transform(function ($item, $key) {
    return $item * 2;
});
// 返回集合中所有唯一的專案:
$unique = $collection->unique();
// 返回鍵重設為連續整數的的新集合:
$values = $collection->values();
// 以一對給定的鍵/數值篩選集合:
$filtered = $collection->where('price', 100);
// 將集合與給定陣列同樣索引的值合併在一起:
$zipped = $collection->zip([100, 200]);

  

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();
// 判斷當環境是否為 local
if ($app->environment('local')){}
// 判斷當環境是否為 local 或 staging...
if ($app->environment('local', 'staging')){}

  

Log

// 記錄器提供了 7 種在 RFC 5424 標準內定義的記錄等級:
// 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();
// 新增監聽器
Log::listen(function($level, $message, $context) {});
              
記錄 SQL 查詢語句 
// 開啟 log
DB::connection()->enableQueryLog();
// 獲取已執行的查詢陣列
DB::getQueryLog();

  

URL

URL::full();
URL::current();
URL::previous();
URL::to('foo/bar', $parameters, $secure);
URL::action('NewsController@item', ['id'=>123]);
// 需要在適當的名稱空間內
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));
// 註冊一個事件監聽器.
// 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');
// 執行資料庫查詢語句
$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');
// 監聽查詢事件
DB::listen(function($sql, $bindings, $time){ code_here; });
// 資料庫事務處理
DB::transaction(function()
{
DB::table('users')->update(['votes' => 1]);
DB::table('posts')->delete();
});
DB::beginTransaction();
DB::rollBack();
DB::commit();
              
查詢語句構造器 
// 取得資料表的所有行
DB::table('name')->get();
// 取資料表的部分資料
DB::table('users')->chunk(100, function($users)
{
  foreach ($users as $user)
  {
      
//
}
});
// 取回資料表的第一條資料
$user = DB::table('users')->where('name', 'John')->first();
DB::table('name')->first();
// 從單行中取出單列資料
$name = DB::table('users')->where('name', 'John')->pluck('name');
DB::table('name')->pluck('column');
// 取多行資料的「列資料」陣列
$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();
// 動態的 Where 字句
$admin = DB::table('users')->whereId(1)->first();
$john = DB::table('users')
      ->whereIdAndEmail(2, '[email protected]')
      ->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');
          
原始表達句
$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');
// 在宣告語句中加入原始的表示式
DB::table('name')->select(DB::raw('count(*) as count, column2'))->get();
          
Inserts / Updates / Deletes / Unions / Pessimistic Locking
// 插入
DB::table('users')->insert(
  ['email' => '[email protected]', 'votes' => 0]
);
$id = DB::table('users')->insertGetId(
  ['email' => '[email protected]', 'votes' => 0]
);
DB::table('users')->insert([
  ['email' => '[email protected]', 'votes' => 0],
  ['email' => '[email protected]', '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() 方法也是可供使用的,呼叫方式與 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

Install and run
// 將其加入到 composer.json 並更新:
composer require "phpunit/phpunit:4.0.*"
// 執行測試 (在專案根目錄下執行)
./vendor/bin/phpunit
              
Asserts
$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();
              
Calling routes
$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');
// 指定預設值
Input::get('key', 'default');
Input::has('key');
Input::all();
// 只取回 'foo' 和 'bar',返回陣列
Input::only('foo', 'bar');
// 取除了 'foo' 的所有使用者輸入陣列
Input::except('foo');
Input::flush();
              
會話週期內 Input
// 清除會話週期內的輸入
Input::flash();
// 清除會話週期內的指定輸入
Input::flashOnly('foo', 'bar');
// 清除會話週期內的除了指定的其他輸入
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);
// 移動一個已上傳的檔案,並設定新的名字
Input::file('name')->move($destinationPath, $fileName);

  

Session

Session::get('key');
// 從會話中讀取一個條目
Session::get('key', 'default');
Session::get('key', function(){ return 'default'; });
// 獲取 session 的 ID
Session::getId();
// 增加一個會話鍵值資料
Session::put('key', 'value');
// 將一個值加入到 session 的陣列中
Session::push('foo.bar','value');
// 返回 session 的所有條目
Session::all();
// 檢查 session 裡是否有此條目
Session::has('key');
// 從 session 中移除一個條目
Session::forget('key');
// 從 session 中移除所有條目
Session::flush();
// 生成一個新的 session 識別符號
Session::regenerate();
// 把一條資料暫存到 session 中
Session::flash('key', 'value');
// 清空所有的暫存資料
Session::reflash();
// 重新暫存當前暫存資料的子集
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);
// 建立一個迴應且修改其頭部資訊的值
$response = Response::make($contents, 200);
$response->header('Content-Type', 'application/json');
return $response;
// 為迴應附加上 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');
// 單例模式例項到服務容器中
App::singleton('foo', function(){ return new Foo; });
// 將已例項化的物件註冊到服務容器中
App::instance('foo', new Foo);
// 註冊繫結規則到服務容器中
App::bind('FooRepositoryInterface', 'BarRepository');
// 給應用註冊一個服務提供者
App::register('FooServiceProvider');
// 監聽容器對某個物件的解析
App::resolving(function($object){});

  

Auth

使用者認證 
// 判斷當前使用者是否已認證(是否已登入)
Auth::check();
// 獲取當前的認證使用者
Auth::user();
// 獲取當前的認證使用者的 ID(未登入情況下會報錯)
Auth::id();
// 通過給定的資訊來嘗試對使用者進行認證(成功後會自動啟動會話)
Auth::attempt(['email' => $email, 'password' => $password]);
// 通過 Auth::attempt() 傳入 true 值來開啟 '記住我' 功能
Auth::attempt($credentials, true);
// 只針對一次的請求來認證使用者
Auth::once($credentials);
// 登入一個指定使用者到應用上
Auth::login(User::find(1));
// 登入指定使用者 ID 的使用者到應用上
Auth::loginUsingId(1);
// 使使用者退出登入(清除會話)
Auth::logout();
// 驗證使用者憑證
Auth::validate($credentials);
// Attempt to authenticate using HTTP Basic Auth
// 使用 HTTP 的基本認證方式來認證
Auth::basic('username');
// Perform a stateless HTTP Basic login attempt
// 執行「HTTP Basic」登入嘗試
Auth::onceBasic();
// 傳送密碼重置提示給使用者
Password::remind($credentials, function($message, $user){});
              
使用者授權 
// 定義許可權
Gate::define('update-post', 'Class@method');
Gate::define('update-post', function ($user, $post) {...});
// 傳遞多個引數
Gate::define('delete-comment', function ($user, $post, $comment) {});

// 檢查許可權
Gate::denies('update-post', $post);
Gate::allows('update-post', $post);
Gate::check('update-post', $post);
// 指定使用者進行檢查
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 表示式
@can('update-post', $post)
@else
@endcan

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

// 控制器授權
$this->authorize('update', $post);
// 指定使用者 $user 授權
$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 Elements
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');
// 生成一個被選中的複選框
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

陣列
// 如果給定的鍵不存在於該陣列,array_add 函式將給定的鍵值對加到陣列中
array_add($array, 'key', 'value');
// 將陣列的每一個數組折成單一陣列
array_collapse($array);
// 函式返回兩個陣列,一個包含原本陣列的鍵,另一個包含原本陣列的值
array_divide($array);
// 把多維陣列扁平化成一維陣列,並用「點」式語法表示深度
array_dot($array);
// 從陣列移除給定的鍵值對
array_except($array, array('key'));
// 返回陣列中第一個通過為真測試的元素
array_first($array, function($key, $value){}, $default);
// 將多維陣列扁平化成一維
// ['Joe', 'PHP', 'Ruby'];
array_flatten(['name' => 'Joe', 'languages' => ['PHP', 'Ruby']]);
// 以「點」式語法從深度巢狀陣列移除給定的鍵值對
array_forget($array, 'foo');
array_forget($array, 'foo.bar');
// 使用「點」式語法從深度巢狀陣列取回給定的值
array_get($array, 'foo', 'default');
array_get($array, 'foo.bar', 'default');
// 使用「點」式語法檢查給定的專案是否存在於陣列中
array_has($array, 'products.desk');
// 從陣列返回給定的鍵值對
array_only($array, array('key'));
// 從陣列拉出一列給定的鍵值對
array_pluck($array, 'key');
// 從陣列移除並返回給定的鍵值對
array_pull($array, 'key');
// 使用「點」式語法在深度巢狀陣列中寫入值
array_set($array, 'key', 'value');
array_set($array, 'key.subkey', 'value');
// 藉由給定閉包結果排序陣列
array_sort($array, function(){});
// 使用 sort 函式遞迴排序陣列
array_sort_recursive();
// 使用給定的閉包過濾陣列
array_where();
// 返回給定陣列的第一個元素
head($array);
// 返回給定陣列的最後一個元素
last($array);
              
路徑
// 取得 app 資料夾的完整路徑
app_path();
// 取得專案根目錄的完整路徑
base_path();
// 取得應用配置目錄的完整路徑
config_path();
// 取得應用資料庫目錄的完整路徑
database_path();
// 取得加上版本號的 Elixir 檔案路徑
elixir();
// 取得 public 目錄的完整路徑
public_path();
// 取得 storage 目錄的完整路徑
storage_path();
              
字串
// 將給定的字串轉換成 駝峰式命名
camel_case($value);
// 返回不包含名稱空間的類名稱
class_basename($class);
class_basename($object);
// 對給定字串執行 htmlentities
e('<html>');
// 判斷字串開頭是否為給定內容
starts_with('Foo bar.', 'Foo');
// 判斷給定字串結尾是否為指定內容
ends_with('Foo bar.', 'bar.');
// 將給定的字串轉換成 蛇形命名
snake_case('fooBar');
// 限制字串的字元數量
str_limit();
// 判斷給定字串是否包含指定內容
str_contains('Hello foo bar.', 'foo');
// 新增給定內容到字串結尾,foo/bar/
str_finish('foo/bar', '/');
// 判斷給定的字串與給定的格式是否符合
str_is('foo*', 'foobar');
// 轉換字串成複數形
str_plural('car');
// 產生給定長度的隨機字串
str_random(25);
// 轉換字串成單數形。該函式目前僅支援英文
str_singular('cars');
// 從給定字串產生網址友善的「slug」
str_slug("Laravel 5 Framework", "-");
// 將給定字串轉換成「首字大寫命名」: FooBar
studly_case('foo_bar');
// 根據你的本地化檔案翻譯給定的語句
trans('foo.bar');
// 根據字尾變化翻譯給定的語句
trans_choice('foo.bar', $count);
              
URLs and Links
// 產生給定控制器行為網址
action('FooController@method', $parameters);
// 根據目前請求的協定(HTTP 或 HTTPS)產生資原始檔網址
asset('img/photo.jpg', $title, $attributes);
// 根據 HTTPS 產生資原始檔網址
secure_asset('img/photo.jpg', $title, $attributes);
// 產生給定路由名稱網址
route($route, $parameters, $absolute = true);
// 產生給定路徑的完整網址
url('path', $parameters = array(), $secure = null);
              
Miscellaneous
// 返回一個認證器例項。你可以使用它取代 Auth facade
auth()->user();
// 產生一個重定向迴應讓使用者回到之前的位置
back();
// 使用 Bcrypt 雜湊給定的數值。你可以使用它替代 Hash facade
bcrypt('my-secret-password');
// 從給定的專案產生集合例項
collect(['taylor', 'abigail']);
// 取得設定選項的設定值
config('app.timezone', $default);
// 產生包含 CSRF 令牌內容的 HTML 表單隱藏欄位
{!! csrf_field() !!}
// 取得當前 CSRF 令牌的內容
$token = csrf_token();
// 輸出給定變數並結束指令碼執行
dd($value);
// 取得環境變數值或返回預設值
$env = env('APP_ENV');
$env = env('APP_ENV', 'production');
// 配送給定事件到所屬的偵聽器
event(new UserRegistered($user));
// 根據給定類、名稱以及總數產生模型工廠建構器
$user = factory(App\User::class)->make();
// 產生擬造 HTTP 表單動作內容的 HTML 表單隱藏欄位
{!! method_field('delete') !!}
// 取得快閃到 session 的舊有輸入數值
$value = old('value');
$value = old('value', 'default');
// 返回重定向器例項以進行 重定向
return redirect('/home');
// 取得目前的請求例項或輸入的專案
$value = request('key', $default = null)
// 建立一個迴應例項或獲取一個迴應工廠例項
return response('Hello World', 200, $headers);
// 可被用於取得或設定單一 session 內容
$value = session('key');
// 在沒有傳遞引數時,將返回 session 例項
$value = session()->get('key');
session()->put('key', $value);
// 返回給定數值
value(function(){ return 'bar'; });
// 取得檢視 例項
return view('auth.login');
// 返回給定的數值
$value = with(new Foo)->work();

  

Config

Config::get('app.timezone');
//指定預設值
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']]);
              
觸發錯誤 
App::abort(404);
$handler->missing(...) in ErrorServiceProvider::boot();
throw new NotFoundHttpException;
              
路由引數 
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]'))
              
// 設定一個可跨路由使用的模式
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

基礎使用 
// 定義一個 Eloquent 模型
class User extends Model {}
// 生成一個 Eloquent 模型
php artisan make:model User
// 指定一個自定義的資料表名稱
class User extends Model {
  protected $table = 'my_users';
}
          
More
Model::create(array('key' => 'value'));
// 通過屬性找到第一條相匹配的資料或創造一條新資料
Model::firstOrCreate(array('key' => 'value'));
// 通過屬性找到第一條相匹配的資料或例項化一條新資料
Model::firstOrNew(array('key' => 'value'));
// 通過屬性找到相匹配的資料並更新,如果不存在即建立
Model::updateOrCreate(array('search_key' => 'search_value'), array('key' => 'value'));
// 使用屬性的陣列來填充一個模型, 用的時候要小心「Mass Assignment」安全問題 !
Model::fill($attributes);
Model::destroy(1);
Model::all();
Model::find(1);
// 使用雙主鍵進行查詢
Model::find(array('first', 'last'));
// 查詢失敗時丟擲異常
Model::findOrFail(1);
// 使用雙主鍵進行查詢, 失敗時丟擲異常
Model::findOrFail(array('first', 'last'));
Model::where('foo', '=', 'bar')->get();
Model::where('foo', '=', 'bar')->first();
Model::where('foo', '=', 'bar')->exists();
// 動態屬性查詢
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);
// 預設的 Eloquent 排序是上升排序
Model::all()->orderBy('column');
Model::all()->orderBy('column','desc');
              
軟刪除 
Model::withTrashed()->where('cars', 2)->get();
// 在查詢結果中包括帶被軟刪除的模型
Model::withTrashed()->where('cars', 2)->restore();
Model::where('cars', 2)->forceDelete();
// 查詢只帶有軟刪除的模型
Model::onlyTrashed()->where('cars', 2)->get();
              
模型關聯
// 一對一 - User::phone()
return $this->hasOne('App\Phone', 'foreign_key', 'local_key');
// 一對一 - Phone::user(), 定義相對的關聯
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');
// 多對多 - 自動維護 created_at 和 updated_at 時間戳
return $this->belongsToMany('App\Role')->withTimestamps();

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

// 多型關聯 - Photo::imageable()
return $this->morphTo();
// 多型關聯 - Staff::photos()
return $this->morphMany('App\Photo', 'imageable');
// 多型關聯 - Product::photos()
return $this->morphMany('App\Photo', 'imageable');
// 多型關聯 - 在 AppServiceProvider 中註冊你的「多型對照表」
Relation::morphMap([
    'Post' => App\Post::class,
    'Comment' => App\Comment::class,
]);

// 多型多對多關聯 - 涉及資料庫表: 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');

// 查詢關聯
$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();

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

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

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

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

// 附加多對多關係
$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]);

// 任何不在給定陣列中的 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 配置資訊
              
// 關閉模型插入或更新操作引發的 「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');
// 建立一個永久有效的 cookie
Cookie::forever('key', 'value');
// 建立一個 N 分鐘有效的 cookie
Cookie::make('key', 'value', 'minutes');
// 在迴應之前先積累 cookie,迴應時統一返回
Cookie::queue('key', 'value', 'minutes');
// 移除 Cookie
Cookie::forget('key');
// 從 response 傳送一個 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();
// 判斷當前請求的 URI 是否可被匹配
Request::is('foo/*');
// 獲取 URI 的分段值 (索引從 1 開始)
Request::segment(1);
// 從請求中取回頭部資訊
Request::header('Content-Type');
// 從請求中取回伺服器變數
Request::server('PATH_INFO');
// 判斷請求是否是 AJAX 請求
Request::ajax();
// 判斷請求是否使用 HTTPS
Request::secure();
// 獲取請求方法
Request::method();
// 判斷請求方法是否是指定型別的
Request::isMethod('post');
// 獲取原始的 POST 資料
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();
// 重定向到命名路由(根據命名路由算出 URL)
return Redirect::route('foobar');
return Redirect::route('foobar', array('value'));
return Redirect::route('foobar', array('key' => 'value'));
// 重定向到控制器動作(根據控制器動作算出 URL)
return Redirect::action('FooController@index');
return Redirect::action('FooController@baz', array('value'));
return Redirect::action('FooController@baz', array('key' => 'value'));
// 跳轉到目的地址,如果沒有設定則使用預設值 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){});
// 零時將傳送郵件請求寫入 log,方便測試
Mail::pretend();
              
訊息
// 這些都能在 $message 例項中使用, 並可傳入到 Mail::send() 或 Mail::queue()
$message->from('[email protected]', 'Mr. Example');
$message->sender('[email protected]', 'Mr. Example');
$message->returnPath('[email protected]');
$message->to('[email protected]', 'Mr. Example');
$message->cc('[email protected]', 'Mr. Example');
$message->bcc('[email protected]', 'Mr. Example');
$message->replyTo('[email protected]', 'Mr. Example');
$message->subject('Welcome to the Jungle');
$message->priority(2);
$message->attach('foo\bar.txt', $options);
// 使用記憶體資料作為附件
$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);
// 註冊一個檢視構造器
View::composer('viewname', function($view){});
// 註冊多個檢視到一個檢視構造器中
View::composer(array('view1', 'view2'), function($view){});
// 註冊一個檢視構造器類
View::composer('viewname', 'FooComposer');
View::creator('viewname', function($view){});

  

Blade

// 區塊佔位
@yield('name')
// 擴展布局模板
@extends('layout.name')
// 實現命名為 name 的區塊(yield 佔位的地方)
@section('name')
@stop
// 可繼承內容區塊
@section('sidebar')
@show
// 繼承父模板內容(@show 的區塊內容)
@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

// 輸出內容,被轉義過的
{{ $var }}
// 輸出未轉義內容,5.0 特性
{!! $var !!}
{{-- Blade 註釋,不會被輸出到頁面中 --}}
// 三元表示式的簡寫,以下相當於「$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)
// 生成更加真實的 "隨機" 字母數字字串.
Str::random($length = 16)
// 生成一個 "隨機" 字母數字字串.
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)