Laravel 速查表
可搜尋、可列印的 Laravel 參考手冊——Artisan、路由、Eloquent、查詢建構器、遷移、Blade、驗證以及集合。免費。
Artisan CLI
14php artisan serve
啟動本機開發伺服器
php artisan make:model Post -mcr
含遷移、控制器與資源的模型
php artisan make:controller PostController
產生新的控制器類別
php artisan make:migration create_posts_table
建立新的遷移檔
php artisan migrate
執行待處理的資料庫遷移
php artisan migrate:fresh --seed
捨棄所有資料表、重新遷移並填充
php artisan db:seed
執行資料庫填充器
php artisan tinker
開啟互動式 REPL shell
php artisan route:list
列出所有已註冊的路由
php artisan optimize
快取設定、路由與視圖
php artisan queue:work
處理佇列中的工作
php artisan schedule:work
在前景執行排程器
php artisan storage:link
將 storage 符號連結到 public 路徑
php artisan key:generate
產生應用程式金鑰
路由
13Route::get('/users', [UserController::class, 'index'])
定義指向控制器的 GET 路由
Route::post('/users', [UserController::class, 'store'])
定義 POST 路由
Route::put('/users/{user}', [UserController::class, 'update'])
定義 PUT 路由
Route::patch('/users/{user}', [UserController::class, 'update'])
定義 PATCH 路由
Route::delete('/users/{user}', [UserController::class, 'destroy'])
定義 DELETE 路由
Route::get('/users/{id}', $fn)
必要的路由參數
Route::get('/users/{id?}', $fn)
可選的路由參數
Route::get('/profile', $fn)->name('profile')
為路由命名以產生 URL
Route::get('/admin', $fn)->middleware('auth')
為路由附加中介軟體
Route::resource('posts', PostController::class)
註冊 RESTful 資源路由
Route::prefix('admin')->group(function () {})
將路由分組於 URI 前綴下
Route::controller(PostController::class)->group($fn)
將路由分組至單一控制器
Route::fallback($fn)
處理未匹配的路由 (404)
控制器
10php artisan make:controller PostController --resource
含 CRUD 方法的資源控制器
public function __invoke(Request $request)
單一動作可呼叫控制器
public function index() {}
列出資源 (resource 方法)
public function store(Request $request) {}
儲存新資源
public function show(Post $post) {}
顯示單一資源 (路由模型繫結)
public function __construct(PostService $svc) {}
透過建構子注入相依項
return view('posts.index', ['posts' => $posts])
回傳帶資料的 Blade 視圖
return response()->json($data)
回傳 JSON 回應
return redirect()->route('posts.index')
重新導向到具名路由
return back()
重新導向到前一頁
Eloquent ORM
14Post::all()
取得每筆記錄
Post::find($id)
依主鍵尋找記錄
Post::where('active', true)->first()
符合條件的第一筆記錄
Post::create(['title' => 'Hi'])
批量指派並儲存記錄
$post->update(['title' => 'Edited'])
更新現有模型
$post->delete()
刪除模型實例
Post::firstOrCreate(['slug' => $slug])
尋找或建立符合的記錄
Post::updateOrCreate($attrs, $values)
找到則更新,否則建立
Post::with('author')->get()
預先載入關聯
public function comments() { return $this->hasMany(Comment::class); }
一對多關聯
public function author() { return $this->belongsTo(User::class); }
反向的一對多關聯
protected $fillable = ['title', 'body'];
可批量指派的屬性
protected function casts(): array { return ['published_at' => 'datetime']; }
屬性轉型 (casts() 方法)
Post::onlyTrashed()->restore()
還原軟刪除的記錄
查詢建構器
13DB::table('users')->get()
從資料表取得所有列
DB::table('users')->where('votes', '>', 100)->get()
依條件篩選列
DB::table('users')->join('posts', 'users.id', '=', 'posts.user_id')
內部連接兩個資料表
DB::table('users')->orderBy('name')->get()
依欄位排序結果
DB::table('orders')->groupBy('status')->get()
依欄位將列分組
DB::table('users')->select('name', 'email')->get()
選取特定欄
DB::table('users')->insert(['name' => 'Sam'])
插入新列
DB::table('users')->where('id', 1)->update(['votes' => 1])
更新符合的列
DB::table('users')->pluck('email')
取得單一欄位為集合
DB::table('users')->count()
計算符合的列數
DB::table('users')->where('id', 1)->exists()
檢查是否有列存在
DB::table('users')->paginate(15)
將結果分頁
DB::table('users')->chunk(100, $fn)
以區塊處理結果
遷移與結構描述
12Schema::create('posts', function (Blueprint $table) {})
建立新資料表
$table->id()
自動遞增的主鍵
$table->string('title')
VARCHAR 欄位
$table->integer('votes')
整數欄位
$table->boolean('active')
布林欄位
$table->timestamps()
created_at 與 updated_at 欄位
$table->foreignId('user_id')->constrained()
帶約束的外鍵
$table->string('note')->nullable()
允許 NULL 值
$table->boolean('active')->default(true)
設定預設值
$table->index('slug')
為欄位新增索引
$table->unique('email')
新增唯一約束
$table->dropColumn('votes')
捨棄欄位
Blade 範本
14@if ($ok) ... @elseif ($x) ... @else ... @endif
條件式渲染
@foreach ($posts as $post) ... @endforeach
走訪集合
@forelse ($posts as $post) ... @empty ... @endforelse
帶空集合後備的迴圈
{{ $variable }}
輸出已跳脫的內容
{!! $html !!}
輸出未跳脫的原始 HTML
@extends('layouts.app')
繼承自版面配置
@section('content') ... @endsection
定義版面區段
@yield('content')
在版面中輸出區段
@include('partials.nav')
引入另一個視圖
<x-alert type="error" />
渲染 Blade 元件
@csrf
表單用的 CSRF token 欄位
@auth ... @endauth
對已驗證使用者顯示內容
@can('update', $post) ... @endcan
授權 gate 檢查
{{ $loop->index }}
@foreach 內的迴圈變數
驗證
12$request->validate(['title' => 'required'])
內嵌驗證請求資料
'email' => 'required|email'
必填且有效的電子郵件規則
'name' => 'required|max:255'
必填且有長度上限
'email' => 'unique:users,email'
在資料表中必須唯一
'age' => 'nullable|integer|min:18'
可選的整數且有最小值
'role' => ['required', Rule::in(['admin', 'user'])]
限制於允許的值
php artisan make:request StorePostRequest
產生 Form Request 類別
public function rules(): array { return [...]; }
Form Request 驗證規則
public function authorize(): bool { return true; }
Form Request 授權
public function messages(): array { return [...]; }
自訂驗證訊息
$validator = Validator::make($data, $rules)
手動建立驗證器
$request->validated()
僅取得已驗證的輸入
請求與回應
10request()->input('name')
取得輸入值
request()->query('page')
取得查詢字串值
request()->all()
以陣列取得所有輸入
request()->only(['name', 'email'])
取得部分輸入
request()->has('name')
檢查輸入是否存在
response()->json(['ok' => true])
回傳 JSON 回應
redirect()->route('home')->with('status', 'Saved')
重新導向並附閃存訊息
back()->withInput()
重新導向回上頁並保留舊輸入
abort(404)
拋出 HTTP 例外
abort_if($user->banned, 403)
有條件地中止請求
集合
13$collection->map(fn ($x) => $x * 2)
轉換每個項目
$collection->filter(fn ($x) => $x > 0)
保留符合的項目
$collection->each(fn ($x) => $x->save())
為每個項目執行回呼
$collection->pluck('name')
擷取單一欄位
$collection->reduce(fn ($c, $x) => $c + $x, 0)
歸納為單一值
$collection->sortBy('created_at')
依鍵排序
$collection->groupBy('status')
依鍵將項目分組
$collection->where('active', true)
依鍵值對篩選
$collection->first()
取得第一個項目
$collection->contains('name', 'Sam')
檢查是否有符合項目
$collection->sum('price')
加總某欄位
$collection->flatten()
攤平巢狀集合
$collection->toArray()
轉換為普通陣列
驗證與中介軟體
11Auth::user()
取得已驗證的使用者
Auth::check()
檢查使用者是否已登入
Auth::id()
取得已驗證的使用者 ID
Auth::login($user)
讓使用者登入
Auth::logout()
將目前使用者登出
auth()->user()
目前使用者的輔助函式
Route::get('/home', $fn)->middleware('auth')
以驗證保護路由
Gate::allows('update', $post)
檢查授權 gate
$user->can('update', $post)
依原則檢查權限
php artisan make:policy PostPolicy --model=Post
產生授權原則
php artisan make:middleware EnsureTokenIsValid
產生中介軟體類別
輔助與其他
12config('app.name')
讀取設定值
env('APP_DEBUG', false)
讀取環境變數
route('posts.show', $post)
產生指向具名路由的 URL
url('/dashboard')
產生完整限定的 URL
asset('css/app.css')
公開資源的 URL
old('email')
取得先前閃存的輸入
now()->addDays(7)
目前的 Carbon 時間戳
Str::slug('My Title')
字串輔助函式 (slugify)
collect([1, 2, 3])->sum()
從陣列建立集合
cache()->remember('key', 60, $fn)
將值快取一段時間
dd($value)
傾印值並中止
Storage::put('file.txt', $contents)
將檔案寫入 storage
沒有條目符合「:q」。
需要協助?
使用此工具時遇到問題?請告訴我們的團隊。