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

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

Laravel 速查表

Laravel 手冊

Artisan

// 針對命令顯示幫助信息
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
// 顯示當前命令行運行的環(huán)境
php artisan --env
// -v|vv|vvv 通過增加 v 的個數(shù)來控制命令行輸出內(nèi)容的詳盡情況: 1 個代表正常輸出, 2 個代表輸出更多消息, 3 個代表調(diào)試
php artisan --verbose
// 移除編譯優(yōu)化過的文件 (storage/frameworks/compiled.php)
php artisan clear-compiled
// 顯示當前框架運行的環(huán)境
php artisan env
// 顯示某個命令的幫助信息
php artisan help
// 顯示所有可用的命令
php artisan list
// 進入應(yīng)用交互模式
php artisan tinker
// 配合 dump() 函數(shù)調(diào)試數(shù)據(jù)
php artisan dump-server
// 進入維護模式
php artisan down
// 退出維護模式
php artisan up
// 優(yōu)化框架性能
 // --force    強制編譯已寫入文件 (storage/frameworks/compiled.php)
 // --psr      不對 Composer 的 dump-autoload 進行優(yōu)化
php artisan optimize [--force] [--psr]
// 更改前端預設(shè)
// type_name (可以是 none, bootstrap, vue, react)
php artisan preset [options] [--] type_name
// 啟動內(nèi)置服務(wù)器
php artisan serve
// 更改默認端口
php artisan serve --port 8080
// 使其在本地服務(wù)器外也可正常工作
php artisan serve --host 0.0.0.0
// 更改應(yīng)用命名空間
php artisan app:name namespace
// 清除過期的密碼重置令牌
php artisan auth:clear-resets

// 清空應(yīng)用緩存
php artisan cache:clear
// 移除 key_name 對應(yīng)的緩存
php artisan cache:forget key_name [<store>]
// 創(chuàng)建緩存數(shù)據(jù)庫表 migration
php artisan cache:table

// 合并所有的配置信息為一個,提高加載速度
php artisan config:cache
// 移除配置緩存文件
php artisan config:clear

// 程序內(nèi)部調(diào)用 Artisan 命令
$exitCode = Artisan::call('config:cache');
// 運行所有的 seed 假數(shù)據(jù)生成類
 // --class      可以指定運行的類,默認是: "DatabaseSeeder"
 // --database   可以指定數(shù)據(jù)庫
 // --force      當處于生產(chǎn)環(huán)境時強制執(zhí)行操作
php artisan db:seed [--class[="..."]] [--database[="..."]] [--force]

// 基于注冊的信息,生成遺漏的 events 和 handlers
php artisan event:generate
// 羅列所有事件和監(jiān)聽器
php artisan event:list
// 緩存事件和監(jiān)聽器
php artisan event:cache
// 清除事件和監(jiān)聽器緩存
php artisan event:clear

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

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

// 發(fā)布本地化翻譯文件到 resources 文件下
// locales: 逗號分隔,如 zh_CN,tk,th [默認是: "all"]
php artisan lang:publish [options] [--] [<locales>]

// 創(chuàng)建用戶認證腳手架
php artisan make:auth
// 創(chuàng)建 Channel 類
php artisan make:channel name
// 在默認情況下, 這將創(chuàng)建未加入隊列的自處理命令
 // 通過 --handler 標識來生成一個處理器, 用 --queued 來使其入隊列.
php artisan make:command [--handler] [--queued] name
// 創(chuàng)建一個新的 Artisan 命令
 //  --command     命令被調(diào)用的名稱。 (默認為: "command:name")
php artisan make:console [--command[="..."]] name
// 創(chuàng)建一個新的資源控制器
 // --plain      生成一個空白的控制器類
php artisan make:controller [--plain] name
php artisan make:controller App\\Admin\\Http\\Controllers\\DashboardController
// 創(chuàng)建一個新的事件類
php artisan make:event name
// 創(chuàng)建異常類
php artisan make:exception name
// 創(chuàng)建模型工廠類
php artisan make:factory name
// 創(chuàng)建一個隊列任務(wù)文件
php artisan make:job 
// 創(chuàng)建一個監(jiān)聽者類
php artisan make:listener name
// 創(chuàng)建一個新的郵件類
php artisan make:mail name
// 創(chuàng)建一個新的中間件類
php artisan make:middleware name
// 創(chuàng)建一個新的遷移文件
 // --create     將被創(chuàng)建的數(shù)據(jù)表.
 // --table      將被遷移的數(shù)據(jù)表.
php artisan make:migration [--create[="..."]] [--table[="..."]] name
// 創(chuàng)建一個新的 Eloquent 模型類
php artisan make:model User
php artisan make:model Models/User
// 新建一個消息通知類
php artisan make:notification TopicRepliedNotification
// 新建一個模型觀察者類
php artisan make:observer UserObserver
// 創(chuàng)建授權(quán)策略
php artisan make:policy PostPolicy
// 創(chuàng)建一個新的服務(wù)提供者類
php artisan make:provider name
// 創(chuàng)建一個新的表單請求類
php artisan make:request name
// 創(chuàng)建一個 API 資源類
php artisan make:resource name
// 新建驗證規(guī)則類
php artisan make:rule name
// 創(chuàng)建模型腳手架
// <name> 模型名稱,如 Post
// -s, --schema=SCHEMA 表結(jié)構(gòu)如:--schema="title:string"
// -a, --validator[=VALIDATOR] 表單驗證,如:--validator="title:required"
// -l, --localization[=LOCALIZATION] 設(shè)置本地化信息,如:--localization="key:value"
// -b, --lang[=LANG] 設(shè)置本地化語言 --
// -f, --form[=FORM] 使用 Illumintate/Html Form 來生成表單選項,默認為 false
// -p, --prefix[=PREFIX] 表結(jié)構(gòu)前綴,默認 false
php artisan make:scaffold  [options] [--] <name>
// 生成數(shù)據(jù)填充類
php artisan make:seeder
// 生成測試類
php artisan make:test

// 數(shù)據(jù)庫遷移
 // --database   指定數(shù)據(jù)庫連接(下同)
 // --force      當處于生產(chǎn)環(huán)境時強制執(zhí)行,不詢問(下同)
 // --path       指定單獨遷移文件地址
 // --pretend    把將要運行的 SQL 語句打印出來(下同)
 // --seed       Seed 任務(wù)是否需要被重新運行(下同)
php artisan migrate [--database[="..."]] [--force] [--path[="..."]] [--pretend] [--seed]
// 創(chuàng)建遷移數(shù)據(jù)庫表
php artisan migrate:install [--database[="..."]]
// Drop 所有數(shù)據(jù)表并重新運行 Migration
php artisan migrate:fresh
// 重置并重新運行所有的 migrations
 // --seeder     指定主 Seeder 的類名
php artisan migrate:refresh [--database[="..."]] [--force] [--seed] [--seeder[="..."]]
// 回滾所有的數(shù)據(jù)庫遷移
php artisan migrate:reset [--database[="..."]] [--force] [--pretend]
// 回滾最最近一次運行的遷移任務(wù)
php artisan migrate:rollback [--database[="..."]] [--force] [--pretend]
// migrations 數(shù)據(jù)庫表信息
php artisan migrate:status

// 為數(shù)據(jù)庫消息通知創(chuàng)建一個表遷移類
php artisan notifications:table
// 清除緩存的 bootstrap 文件
php artisan optimize:clear
// 擴展包自動發(fā)現(xiàn)
php artisan package:discover

// 為隊列數(shù)據(jù)庫表創(chuàng)建一個新的遷移
php artisan queue:table
// 監(jiān)聽指定的隊列
 // --queue      被監(jiān)聽的隊列
 // --delay      給執(zhí)行失敗的任務(wù)設(shè)置延時時間 (默認為零: 0)
 // --memory     內(nèi)存限制大小,單位為 MB (默認為: 128)
 // --timeout    指定任務(wù)運行超時秒數(shù) (默認為: 60)
 // --sleep      等待檢查隊列任務(wù)的秒數(shù) (默認為: 3)
 // --tries      任務(wù)記錄失敗重試次數(shù) (默認為: 0)
php artisan queue:listen [--queue[="..."]] [--delay[="..."]] [--memory[="..."]] [--timeout[="..."]] [--sleep[="..."]] [--tries[="..."]] [connection]
// 查看所有執(zhí)行失敗的隊列任務(wù)
php artisan queue:failed
// 為執(zhí)行失敗的數(shù)據(jù)表任務(wù)創(chuàng)建一個遷移
php artisan queue:failed-table
// 清除所有執(zhí)行失敗的隊列任務(wù)
php artisan queue:flush
// 刪除一個執(zhí)行失敗的隊列任務(wù)
php artisan queue:forget
// 在當前的隊列任務(wù)執(zhí)行完畢后, 重啟隊列的守護進程
php artisan queue:restart
// 對指定 id 的執(zhí)行失敗的隊列任務(wù)進行重試(id: 失敗隊列任務(wù)的 ID)
php artisan queue:retry id
// 指定訂閱 Iron.io 隊列的鏈接
 // queue: Iron.io 的隊列名稱.
 // url: 將被訂閱的 URL.
 // --type       指定隊列的推送類型.
php artisan queue:subscribe [--type[="..."]] queue url
// 處理下一個隊列任務(wù)
 // --queue      被監(jiān)聽的隊列
 // --daemon     在后臺模式運行
 // --delay      給執(zhí)行失敗的任務(wù)設(shè)置延時時間 (默認為零: 0)
 // --force      強制在「維護模式下」運行
 // --memory     內(nèi)存限制大小,單位為 MB (默認為: 128)
 // --sleep      當沒有任務(wù)處于有效狀態(tài)時, 設(shè)置其進入休眠的秒數(shù) (默認為: 3)
 // --tries      任務(wù)記錄失敗重試次數(shù) (默認為: 0)
php artisan queue:work [--queue[="..."]] [--daemon] [--delay[="..."]] [--force] [--memory[="..."]] [--sleep[="..."]] [--tries[="..."]] [connection]

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

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

// 為 session 數(shù)據(jù)表生成遷移文件
php artisan session:table
// 創(chuàng)建 "public/storage" 到 "storage/app/public" 的軟鏈接
php artisan storage:link

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

// 緩存視圖文件以提高效率
php artisan view:cache
// 清除視圖文件緩存
php artisan view:clear

Pagination

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

// 獲取當前頁數(shù)據(jù)數(shù)量。
$results->count()
// 獲取當前頁頁碼。
$results->currentPage()
// 獲取結(jié)果集中第一條數(shù)據(jù)的結(jié)果編號。
$results->firstItem()
// 獲取分頁器選項。
$results->getOptions()
// 創(chuàng)建分頁 URL 范圍。
$results->getUrlRange($start, $end)
// 是否有多頁。
$results->hasMorePages()
// 獲取結(jié)果集中最后一條數(shù)據(jù)的結(jié)果編號。
$results->lastItem()
// 獲取最后一頁的頁碼(在 `simplePaginate` 中無效)。
$results->lastPage()
// 獲取下一頁的 URL 。
$results->nextPageUrl()
// 當前而是否為第一頁。
$results->onFirstPage()
// 每頁的數(shù)據(jù)條數(shù)。
$results->perPage()
// 獲取前一頁的 URL。
$results->previousPageUrl()
// 數(shù)據(jù)總數(shù)(在 `simplePaginate` 無效)。
$results->total()
// 獲取指定頁的 URL。
$results->url($page)

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');
// Lang::choice 的別名
trans_choice('messages.apples',  10)
// 輔助函數(shù)
__('messages.welcome')

File

File::exists($path);
File::get($path, $lock = false);
// 加鎖讀取文件內(nèi)容
File::sharedGet($path);
// 獲取文件內(nèi)容,不存在會拋出 FileNotFoundException 異常
File::getRequire($path);
// 獲取文件內(nèi)容, 僅能引入一次
File::requireOnce($file);
// 生成文件路徑的 MD5 哈希
File::hash($path);
// 將內(nèi)容寫入文件
File::put($path, $contents, $lock = false);
// 寫入文件,存在的話覆蓋寫入
File::replace($path, $content);
// 將內(nèi)容添加在文件原內(nèi)容前面
File::prepend($path, $data);
// 將內(nèi)容添加在文件原內(nèi)容后
File::append($path, $data);
// 修改路徑權(quán)限
File::chmod($path, $mode = null);
// 通過給定的路徑來刪除文件
File::delete($paths);
// 將文件移動到新目錄下
File::move($path, $target);
// 將文件復制到新目錄下
File::copy($path, $target);
// 創(chuàng)建硬連接
File::link($target, $link);
// 從文件路徑中提取文件名,不包含后綴
File::name($path);
// 從文件路徑中提取文件名,包含后綴
File::basename($path);
// 獲取文件路徑名稱
File::dirname($path);
// 從文件的路徑地址提取文件的擴展
File::extension($path);
// 獲取文件類型
File::type($path);
// 獲取文件 MIME 類型
File::mimeType($path);
// 獲取文件大小
File::size($path);
// 獲取文件的最后修改時間
File::lastModified($path);
// 判斷給定的路徑是否是文件目錄
File::isDirectory($directory);
// 判斷給定的路徑是否是可讀取
File::isReadable($path);
// 判斷給定的路徑是否是可寫入的
File::isWritable($path);
// 判斷給定的路徑是否是文件
File::isFile($file);
// 查找能被匹配到的路徑名
File::glob($pattern, $flags = 0);
// 獲取一個目錄下的所有文件, 以數(shù)組類型返回
File::files($directory, $hidden = false);
// 獲取一個目錄下的所有文件 (遞歸).
File::allFiles($directory, $hidden = false);
// 獲取一個目錄內(nèi)的目錄
File::directories($directory);
// 創(chuàng)建一個目錄
File::makeDirectory($path, $mode = 0755, $recursive = false, $force = false);
// 移動目錄
File::moveDirectory($from, $to, $overwrite = false);
// 將文件夾從一個目錄復制到另一個目錄下
File::copyDirectory($directory, $destination, $options = null);
// 刪除目錄
File::deleteDirectory($directory, $preserve = false);
// 遞歸式刪除目錄
File::deleteDirectories($directory);
// 清空指定目錄的所有文件和文件夾
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;
});

任務(wù)

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

SFTP 上傳

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

Schema

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

索引

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

外鍵

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

字段類型

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

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

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

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

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

Auth

用戶認證

// 獲取 Auth 對象,等同于 Auth Facade
auth();
// 判斷當前用戶是否已認證(是否已登錄)
Auth::check();
// 判斷當前用戶是否未登錄,與 check() 相反
Auth::guest();
// 自定義看守器 默認為 `web`
Auth::guard();
// 獲取當前的認證用戶
Auth::user();
// 獲取當前的認證用戶的 ID(未登錄情況下會報錯)
Auth::id();
// 通過給定的信息來嘗試對用戶進行認證(成功后會自動啟動會話)
Auth::attempt(['email' => $email, 'password' => $password]);
// 通過 Auth::attempt() 傳入 true 值來開啟 '記住我' 功能
Auth::attempt($credentials, true);
// 注冊嘗試登錄的事件監(jiān)聽器
Auth::attempting($callback);
// 只針對一次的請求來認證用戶
Auth::once($credentials);
// 使用 ID 登錄,無 Cookie 和會話登錄
Auth::onceUsingId($id);
// 登錄一個指定用戶到應(yīng)用上
Auth::login(User::find(1), $remember = false);
// 檢測是否記住了登錄
Auth::viaRemember();
// 登錄指定用戶 ID 的用戶到應(yīng)用上
Auth::loginUsingId(1, $remember = false);
// 使用戶退出登錄(清除會話)
Auth::logout();
// 清除當前用戶的其他會話
Auth::logoutOtherDevices('password', $attribute = 'password');
// 驗證用戶憑證
Auth::validate($credentials);
// 使用 HTTP 的基本認證方式來認證
Auth::basic('username');
// 執(zhí)行「HTTP Basic」登錄嘗試,只認證一次
Auth::onceBasic();
// 發(fā)送密碼重置提示給用戶
Password::remind($credentials, function($message, $user){});

用戶授權(quán)

// 定義權(quán)限
Gate::define('update-post', 'Class@method');
Gate::define('update-post', function ($user, $post) {...});
// 傳遞多個參數(shù)
Gate::define('delete-comment', function ($user, $post, $comment) {});
// 一次性的定義多個 Gate 方法
Gate::resource('posts',  'App\Policies\PostPolicy');
// 檢測權(quán)限是否被定義
Gate::has('update-post');

// 檢查權(quán)限
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);
User::find(1)->cant('update-post', $post);

// 攔截所有檢查,返回 bool
Gate::before(function ($user, $ability) {});
// 設(shè)置每一次驗證的回調(diào)
Gate::after(function ($user, $ability, $result, $arguments) {});

// Blade 模板語法
@can('update-post', $post)
@endcan
// 支持 else 表達式
@can('update-post', $post)
@else
@endcan
// 無權(quán)限判斷
@cannot
@endcannot

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

// 控制器授權(quán)
$this->authorize('update', $post);
// 指定用戶 $user 授權(quán)
$this->authorizeForUser($user, 'update', $post);
// 控制器的 __construct 中授權(quán)資源控制器
$this->authorizeResource(Post::class,  'post');

// AuthServiceProvider->boot() 里修改策略自動發(fā)現(xiàn)的邏輯
Gate::guessPolicyNamesUsing(function ($modelClass) {
    // 返回模型對應(yīng)的策略名稱,如:// 'App\Model\User' => 'App\Policies\UserPolicy',
    return 'App\Policies\\'.class_basename($modelClass).'Policy';
});

// 中間件指定模型實例
Route::put('/post/{post}',  function  (Post $post)  { ... })->middleware('can:update,post');
// 中間件未指定模型實例
Route::post('/post',  function  ()  { ... })->middleware('can:create,App\Post');

Helper

注:數(shù)組和字串函數(shù)將在 5.9 全面廢棄,推薦使用 Arr 和 Str Facade

數(shù)組 & 對象

// 如果給定的鍵不存在于該數(shù)組,Arr::add 函數(shù)將給定的鍵值對加到數(shù)組中
Arr::add(['name' => 'Desk'], 'price', 100); 
// >>> ['name' => 'Desk', 'price' => 100]
// 將數(shù)組的每一個數(shù)組折成單一數(shù)組
Arr::collapse([[1, 2, 3], [4, 5, 6]]);  
// >>> [1, 2, 3, 4, 5, 6]
// 函數(shù)返回兩個數(shù)組,一個包含原本數(shù)組的鍵,另一個包含原本數(shù)組的值
Arr::divide(['key1' => 'val1', 'key2' =>'val2'])
// >>> [["key1","key2"],["val1","val2"]]
// 把多維數(shù)組扁平化成一維數(shù)組,并用「點」式語法表示深度
Arr::dot($array);
// 從數(shù)組移除給定的鍵值對
Arr::except($array, array('key'));
// 返回數(shù)組中第一個通過為真測試的元素
Arr::first($array, function($key, $value){}, $default);
// 將多維數(shù)組扁平化成一維
 // ['Joe', 'PHP', 'Ruby'];
Arr::flatten(['name' => 'Joe', 'languages' => ['PHP', 'Ruby']]);
// 以「點」式語法從深度嵌套數(shù)組移除給定的鍵值對
Arr::forget($array, 'foo');
Arr::forget($array, 'foo.bar');
// 使用「點」式語法從深度嵌套數(shù)組取回給定的值
Arr::get($array, 'foo', 'default');
Arr::get($array, 'foo.bar', 'default');
// 使用「點」式語法檢查給定的項目是否存在于數(shù)組中
Arr::has($array, 'products.desk');
// 從數(shù)組返回給定的鍵值對
Arr::only($array, array('key'));
// 從數(shù)組拉出一列給定的鍵值對
Arr::pluck($array, 'key');
// 從數(shù)組移除并返回給定的鍵值對
Arr::pull($array, 'key');
// 使用「點」式語法在深度嵌套數(shù)組中寫入值
Arr::set($array, 'key', 'value');
Arr::set($array, 'key.subkey', 'value');
// 借由給定閉包結(jié)果排序數(shù)組
Arr::sort($array, function(){});
// 使用 sort 函數(shù)遞歸排序數(shù)組
Arr::sortRecursive();
// 使用給定的閉包過濾數(shù)組
Arr::where();
// 數(shù)組"洗牌"
Arr::shuffle($array,'I-AM-GROOT');
// 數(shù)組包裹(如果不是數(shù)組,就變成數(shù)組,如果是空的,返回[],否則返回原數(shù)據(jù))
Arr::wrap($array);
// 返回給定數(shù)組的第一個元素
head($array);
// 返回給定數(shù)組的最后一個元素
last($array);

路徑

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

字符串

// 將給定的字符串轉(zhuǎn)換成 駝峰式命名
Str::camel($value);
// 返回不包含命名空間的類名稱
class_basename($class);
class_basename($object);
// 對給定字符串運行 htmlentities
e('<html>');
// 判斷字符串開頭是否為給定內(nèi)容
Str::startsWith('Foo bar.', 'Foo');
// 判斷給定字符串結(jié)尾是否為指定內(nèi)容
Str::endsWith('Foo bar.', 'bar.');
// 將給定的字符串轉(zhuǎn)換成 蛇形命名
Str::snake('fooBar');
// 將給定字符串轉(zhuǎn)換成「首字大寫命名」: FooBar
Str::studly('foo_bar');
// 根據(jù)你的本地化文件翻譯給定的語句
trans('foo.bar');
// 根據(jù)后綴變化翻譯給定的語句
trans_choice('foo.bar', $count);

URLs and Links

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

其他

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

Composer

composer create-project laravel/laravel folder_name
composer create-project laravel/laravel folder_name --prefer-dist "5.8.*"
composer install
composer install --prefer-dist
composer update
composer update package/name
composer dump-autoload [--optimize]
composer self-update
composer require [options] [--] [vendor/packages]...
// 全局安裝
composer require global vendor/packages
// 羅列所有擴展包括版本信息
composer show

Environment

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

Log

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

記錄 SQL 查詢語句

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

URL

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

Event

// 1. EventServiceProvider 類里的 $listen 屬性
protected $listen =['App\Events\OrderShipped' => ['App\Listeners\SendShipmentNotification']];
// 2. 生成監(jiān)聽類
php artisan event:generate

// 觸發(fā)命令
Event::fire($event, $payload = [], $halt = false);
Event::dispatch($event, $payload = [], $halt = false);
event($event, $payload = [], $halt = false);
// 觸發(fā)命令并等待
Event::until($event, $payload = []);
// 注冊一個事件監(jiān)聽器.
// void listen(string|array $events, mixed $listener, int $priority)
Event::listen('App\Events\UserSignup', function($bar){});
Event::listen('event.*', function($bar){}); // 通配符監(jiān)聽器
Event::listen('foo.bar', 'FooHandler', 10);
Event::listen('foo.bar', 'BarHandler', 5);
// 你可以直接在處理邏輯中返回 false 來停止一個事件的傳播.
Event::listen('foor.bar', function($event){ return false; });
Event::subscribe('UserEventHandler');
// 獲取所有監(jiān)聽者
Event::getListeners($eventName);
// 移除事件及其對應(yīng)的監(jiān)聽者
Event::forget($event);
// 將事件推入堆棧中等待執(zhí)行
Event::push($event, $payload = []);
// 移除指定的堆棧事件
Event::flush($event);
// 移除所有堆棧中的事件
Event::forgetPushed();

DB

基本使用

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

// 獲取表前綴
DB::getTablePrefix()

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

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

Joins?

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

聚合?

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

原始表達句

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

UnitTest

安裝和運行

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

斷言

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

訪問路由

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

Input

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

會話周期內(nèi) Input

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

Files

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

Session

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

Response

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

Container

App::bind('foo', function($app){ return new Foo; });
App::make('foo');
// 如果存在此類, 則返回
App::make('FooBar');
// 單例模式實例到服務(wù)容器中
App::singleton('foo', function(){ return new Foo; });
// 將已實例化的對象注冊到服務(wù)容器中
App::instance('foo', new Foo);
// 注冊綁定規(guī)則到服務(wù)容器中
App::bind('FooRepositoryInterface', 'BarRepository');
// 綁定基本值
App::when('App\Http\Controllers\UserController')->needs('$variableName')->give($value);
// 標記
$this->app->tag(['SpeedReport',  'MemoryReport'],  'reports');
// 給應(yīng)用注冊一個服務(wù)提供者
App::register('FooServiceProvider');
// 監(jiān)聽容器對某個對象的解析
App::resolving(function($object){});
resolve('HelpSpot\API');

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);
// 開啟隊列監(jiān)聽器
php artisan queue:listen
php artisan queue:listen connection
php artisan queue:listen --timeout=60
// 只處理第一個隊列任務(wù)
php artisan queue:work
// 在后臺模式啟動一個隊列 worker
php artisan queue:work --daemon
// 為失敗的任務(wù)創(chuàng)建 migration 文件
php artisan queue:failed-table
// 監(jiān)聽失敗任務(wù)
php artisan queue:failed
// 通過 id 刪除失敗的任務(wù)
php artisan queue:forget 5
// 刪除所有失敗任務(wù)
php artisan queue:flush
// 因為隊列不會默認使用 PHP memory 參數(shù),需要在隊列指定(單位默認mb)
php artisan queue:work --memory=50

Validation

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

驗證規(guī)則

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

Config

// config/app.php 里的 timezone 配置項
Config::get('app.timezone')
Config::get('app.timezone', 'default');
Config::set('database.default', 'sqlite');
// config() 等同于 Config Facade
config()->get('app.timezone');
config('app.timezone', 'default');   // get
config(['database.default' => 'sqlite']); // set

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']]);
// 批量注冊資源路由
Route::resources(['foo' => 'FooController', 'bar' => 'BarController'])
Route::resources(['foo' => 'FooController', 'bar' => 'BarController'], ['only' => ['index', 'show']])
Route::resources(['foo' => 'FooController', 'bar' => 'BarController'], ['except' => ['update', 'destroy']])

觸發(fā)錯誤?

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

路由參數(shù)?

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

HTTP 請求方式

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

安全路由 (TBD)

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

路由約束

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

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

HTTP 中間件?

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

命名路由

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

路由前綴

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

路由命名空間

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

子域名路由

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

Model

基礎(chǔ)使用?

// 定義一個 Eloquent 模型
class User extends Model {}
// 生成一個 Eloquent 模型
php artisan make:model User
// 生成一個 Eloquent 模型的時候,順便生成遷移文件
php artisan make:model User --migration OR -m
// 指定一個自定義的數(shù)據(jù)表名稱
class User extends Model {
  protected $table = 'my_users';
}

More

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

軟刪除?

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

事件

Model::retrieved(function($model){});
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::restoring(function($model){});
Model::restored(function($model){});
Model::observe(new FooObserver);

Eloquent 配置信息

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

Cache

// 獲取緩存對象,約等于 Cache
cache()
// 注意 5.8 緩存單位為「秒」,之前版本為「分」
Cache::put('key', 'value', $seconds);
// 未設(shè)置過期時間將永久有效
Cache::put('key',  'value'); 
Cache::add('key', 'value', $seconds);
Cache::forever('key', 'value');
Cache::sear('key', function(){ return 'value' });
Cache::remember('key', $seconds, 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'; });
// 取到數(shù)據(jù)之后再刪除它
Cache::pull('key'); 
// 清空所有緩存
Cache::flush();
Cache::increment('key');
Cache::increment('key', $amount);
Cache::decrement('key');
Cache::decrement('key', $amount);
Cache::tags('my-tag')->put('key','value', $seconds);
Cache::tags('my-tag')->has('key');
Cache::tags('my-tag')->get('key');
Cache::tags(['people',  'artists'])->put('John',  $john,  $seconds);
Cache::tags('my-tag')->forget('key');
Cache::tags('my-tag')->flush();
Cache::tags(['people',  'authors'])->flush();
Cache::section('group')->put('key', $value);
Cache::section('group')->get('key');
Cache::section('group')->flush();
Cache::tags(['people',  'artists'])->put('John',  $john,  $seconds);
// 輔助函數(shù)
cache('key');
cache(['key' => 'value'], $seconds);
cache(['key' => 'value'], now()->addMinutes(10));
cache()->remember('users',  $seconds,  function() { return  User::all(); });
// 指定緩存存儲
Cache::store('file')->get('foo');
Cache::store('redis')->put('name',  'Jack',  600);  // 10 分鐘
// 事件
'Illuminate\Cache\Events\CacheHit' => ['App\Listeners\LogCacheHit',],
'Illuminate\Cache\Events\CacheMissed' => ['App\Listeners\LogCacheMissed',],
'Illuminate\Cache\Events\KeyForgotten' => ['App\Listeners\LogKeyForgotten',],
'Illuminate\Cache\Events\KeyWritten' => ['App\Listeners\LogKeyWritten',],

Cookie

// 等于 Cookie
cookie();
request()->cookie('name');
Cookie::get('key');
Cookie::get('key', 'default');
// 創(chuàng)建一個永久有效的 cookie
Cookie::forever('key', 'value');
// 創(chuàng)建一個 N 分鐘有效的 cookie
Cookie::make('key', 'value', 'minutes');
cookie('key', 'value', 'minutes');
// 在回應(yīng)之前先積累 cookie,回應(yīng)時統(tǒng)一返回
Cookie::queue('key', 'value', 'minutes');
// 移除 Cookie
Cookie::forget('key');
// 從 response 發(fā)送一個 cookie
$response = Response::make('Hello World');
$response->withCookie(Cookie::make('name', 'value', $minutes));
// 設(shè)置未加密 Cookie app/Http/Middleware/EncryptCookies.php
EncryptCookies->except = ['cookie_name_1'];

Request

//獲取請求參數(shù) form-data 與 raw 請求類型
request()->input();
// 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');
// 從請求中取回服務(wù)器變量
Request::server('PATH_INFO');
// 判斷請求是否是 AJAX 請求
Request::ajax();
// 判斷請求是否使用 HTTPS
Request::secure();
// 獲取請求方法
Request::method();
// 判斷請求方法是否是指定類型的
Request::isMethod('post');
// 獲取原始的 POST 數(shù)據(jù)
Request::instance()->getContent();
// 獲取請求要求返回的格式
Request::format();
// 判斷 HTTP Content-Type 頭部信息是否包含 */json
Request::isJson();
// 判斷 HTTP Accept 頭部信息是否為 application/json
Request::wantsJson();

Redirect

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

Mail

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

消息

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

View

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

Blade

// 輸出內(nèi)容,被轉(zhuǎn)義過的
{{ $var }}
// 輸出未轉(zhuǎn)義內(nèi)容
{!! $var !!}
{{-- Blade 注釋,不會被輸出到頁面中 --}}
// 三元表達式的簡寫,以下相當于「isset($name) ? $name : 'Default'」
{{ $name ?? 'Default' }}
// 等同 echo json_encode($array);
@json($array);
// 禁用 HTML 實體雙重編碼
Blade::withoutDoubleEncoding();
// 書寫 PHP 代碼
@php 
@endphp
@csrf // CSRF 域
@method('PUT') // HTML 表單偽造方法 _method
// 服務(wù)容器注入,后調(diào)用 {{ $metrics->monthlyRevenue() }}
@inject('metrics', 'App\Services\MetricsService')

包含和繼承

// 擴展布局模板
@extends('layout.name')
// 區(qū)塊占位
@yield('name')
// 第一種、直接填入擴展內(nèi)容
@section('title',  'Page Title')
// 第二種、實現(xiàn)命名為 name 的區(qū)塊(yield 占位的地方)
@section('sidebar')
    // 繼承父模板內(nèi)容
    @parent
@endsection
// 可繼承內(nèi)容區(qū)塊
@section('sidebar')
@show
// 繼承父模板內(nèi)容(@show 的區(qū)塊內(nèi)容)
@parent
// 包含子視圖
@include('view.name')
// 包含子視圖,并傳參
@include('view.name', ['key' => 'value']);
@includeIf('view.name',  ['some'  =>  'data'])
@includeWhen($boolean,  'view.name',  ['some'  =>  'data'])
// 包含給定視圖數(shù)組中第一個存在的視圖
@includeFirst(['custom.admin',  'admin'],  ['some'  =>  'data'])
// 加載本地化語句
@lang('messages.name')
@choice('messages.name', 1);
// 檢查片斷是否存在
@hasSection('navigation')
        @yield('navigation')
@endif
// 迭代 jobs 數(shù)組并包含
@each('view.name',  $jobs,  'job')
@each('view.name',  $jobs,  'job',  'view.empty')
// 堆棧
@stack('scripts')
@push('scripts')
    <script src="/example.js"></script>
@endpush
// 棧頂插入
@prepend('scripts')
@endprepend
// 組件
@component('alert', ['foo' => 'bar'])
    @slot('title')
    @endslot
@endcomponent
// 注冊別名 @alert(['type' => 'danger'])...@endalert
Blade::component('components.alert',  'alert');

條件語句

@if (count($records) === 1)
@elseif  (count($records) > 1)
@else
@endif
// 登錄情況下
@unless (Auth::check())
@endunless
// $records 被定義且不是  null...
@isset($records)
@endisset
// $records 為空...
@empty($records)
@endempty
// 此用戶身份已驗證...
@auth // 或 @auth('admin')
@endauth
// 此用戶身份未驗證...
@guest // 或 @guest('admin')
@endguest
@switch($i)
    @case(1)
        @break
    @default
        // 默認
@endswitch

循環(huán)

// for 循環(huán)
@for ($i = 0; $i < 10; $i++)
@endfor
// foreach 迭代
@foreach ($users as $user)
@endforeach
// 迭代如果為空的話
@forelse ($users as $user)
@empty
@endforelse
// while 循環(huán)
@while (true)
@endwhile
// 終結(jié)循環(huán)
@continue
@continue($user->type  ==  1) // 帶條件
// 跳過本次迭代
@break
@break($user->number  ==  5) // 帶條件
// 循環(huán)變量
$loop->index        // 當前迭代的索引(從 0 開始計數(shù))。
$loop->iteration    // 當前循環(huán)迭代 (從 1 開始計算)。
$loop->remaining    // 循環(huán)中剩余迭代的數(shù)量。
$loop->count        // 被迭代的數(shù)組元素的總數(shù)。
$loop->first        // 是否為循環(huán)的第一次迭代。
$loop->last         // 是否為循環(huán)的最后一次迭代。
$loop->depth        // 當前迭代的嵌套深度級數(shù)。
$loop->parent       // 嵌套循環(huán)中,父循環(huán)的循環(huán)變量

JavaScript 代碼

// JS 框架,保留雙大括號,以下會編譯為 {{ name }}
@{{ name }}
// 大段 JavaScript 變量,verbatim 里模板引擎將不解析
@verbatim
        Hello, {{ javascriptVariableName }}.
@endverbatim

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)
// 生成更加真實的 "隨機" 字母數(shù)字字符串.
Str::random($length = 16)
// 生成一個 "隨機" 字母數(shù)字字符串.
Str::quickRandom($length = 16)
Str::upper($value)
Str::title($value)
Str::singular($value)
Str::slug($title, $separator = '-')
Str::snake($value, $delimiter = '_')
Str::startsWith($haystack, $needles)
Str::studly($value)
Str::macro($name, $macro)

Collection

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

Storage

// 寫入文件
Storage::put('avatars/1', $fileContents);
// 指定磁盤
Storage::disk('local')->put('file.txt', 'Contents');
Storage::get('file.jpg');
Storage::exists('file.jpg');
Storage::download('file.jpg',  $name,  $headers);
Storage::url('file.jpg');
Storage::temporaryUrl('file.jpg', now()->addMinutes(5));
Storage::size('file.jpg');
Storage::lastModified('file.jpg');
// 自動為文件名生成唯一的ID...  
Storage::putFile('photos',  new  File('/path/to/photo'));
// 手動指定文件名...  
Storage::putFileAs('photos', new  File('/path/to/photo'), 'photo.jpg');
Storage::prepend('file.log', 'Prepended Text');
Storage::append('file.log', 'Appended Text');
Storage::copy('old/file.jpg', 'new/file.jpg');
Storage::move('old/file.jpg', 'new/file.jpg');
Storage::putFileAs('avatars', $request->file('avatar'), Auth::id());
// 「可見性」是對多個平臺的文件權(quán)限的抽象
Storage::getVisibility('file.jpg');
Storage::setVisibility('file.jpg',  'public')
Storage::delete('file.jpg');
Storage::delete(['file.jpg',  'file2.jpg']);
// 獲取目錄下的所有的文件
Storage::files($directory);
Storage::allFiles($directory);
// 獲取目錄下的所有目錄
Storage::directories($directory);
Storage::allDirectories($directory);
// 創(chuàng)建目錄
Storage::makeDirectory($directory);
// 刪除目錄
Storage::deleteDirectory($directory);