Laravel 5 速查表

Artisan 

// 在版本 5.1.11 新添加,見 http://d.laravel-china.org/docs/5.1/authorization#creating-policiesphp 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 // 建立緩存數據庫表 migrationphp 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 和 handlersphp 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] 

Composer 

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

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 中間件 
// 爲路由指定 MiddlewareRoute::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(){});

Environment 

$environment = app()->environment(); $environment = App::environment(); $environment = $app->environment(); // 判斷當環境是否爲 localif ($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 查詢語句 
// 開啓 logDB::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, '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');
原始表達句
$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'); // 返回 voidDB::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' => '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() 方法也是可供使用的,調用方式與 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(); 

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(); 

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'); 

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);

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() 

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);

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'); // 建立一個永久有效的 cookieCookie::forever('key', 'value'); // 建立一個 N 分鐘有效的 cookieCookie::make('key', 'value', 'minutes'); // 在迴應以前先積累 cookie,迴應時統一返回Cookie::queue('key', 'value', 'minutes'); // 移除 CookieCookie::forget('key'); // 從 response 發送一個 cookie$response = Response::make('Hello World'); $response->withCookie(Cookie::make('name', 'value', $minutes));

Session 

Session::get('key'); // 從會話中讀取一個條目Session::get('key', 'default'); Session::get('key', function(){ return 'default'; }); // 獲取 session 的 IDSession::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'));

Request 

// url: http://xx.com/aa/bbRequest::url(); // 路徑: /aa/bbRequest::path(); // 獲取請求 Uri: /aa/bb/?c=dRequest::getRequestUri(); // 返回用戶的 IPRequest::ip(); // 獲取 Uri: http://xx.com/aa/bb/?c=dRequest::getUri(); // 獲取查詢字符串: c=dRequest::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(); // 判斷請求是否使用 HTTPSRequest::secure(); // 獲取請求方法Request::method(); // 判斷請求方法是不是指定類型的Request::isMethod('post'); // 獲取原始的 POST 數據Request::instance()->getContent(); // 獲取請求要求返回的格式Request::format(); // 判斷 HTTP Content-Type 頭部信息是否包含 */jsonRequest::isJson(); // 判斷 HTTP Accept 頭部信息是否爲 application/jsonRequest::wantsJson();

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; // 爲迴應附加上 cookiereturn Response::make($content) ->withCookie(Cookie::make('key', 'value'));

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/barreturn Redirect::intended('foo/bar');

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){});

Security

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

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 traitUser::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); 

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@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); // 使用內存數據做爲附件$message->attachData('bar', 'Data Name', $options); // 附帶文件,並返回 CID$message->embed('foo\bar.txt'); $message->embedData('foo', 'Data Name', $options); // 獲取底層的 Swift Message 對象$message->getSwiftMessage();

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 // 在後臺模式啓動一個隊列 workerphp 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 

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 }}

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(); 

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 linkHTML::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); 

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) 

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); // 對給定字符串運行 htmlentitiese('<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", "-"); // 將給定字符串轉換成「首字大寫命名」: FooBarstudly_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 facadeauth()->user(); // 產生一個重定向迴應讓用戶回到以前的位置back(); // 使用 Bcrypt 哈希給定的數值。你可使用它替代 Hash facadebcrypt('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(); 

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]); 
相關文章
相關標籤/搜索