所有工具
免費

可搜尋、可列印的 Laravel 參考手冊——Artisan、路由、Eloquent、查詢建構器、遷移、Blade、驗證以及集合。免費。

Artisan CLI

14
php artisan serve
Start the local development server
php artisan make:model Post -mcr
Model with migration, controller and resource
php artisan make:controller PostController
Generate a new controller class
php artisan make:migration create_posts_table
Create a new migration file
php artisan migrate
Run pending database migrations
php artisan migrate:fresh --seed
Drop all tables, re-migrate and seed
php artisan db:seed
Run the database seeders
php artisan tinker
Open an interactive REPL shell
php artisan route:list
List all registered routes
php artisan optimize
Cache config, routes and views
php artisan queue:work
Process jobs on the queue
php artisan schedule:work
Run the scheduler in the foreground
php artisan storage:link
Symlink storage to the public path
php artisan key:generate
Generate the application key

Routing

13
Route::get('/users', [UserController::class, 'index'])
Define a GET route to a controller
Route::post('/users', [UserController::class, 'store'])
Define a POST route
Route::put('/users/{user}', [UserController::class, 'update'])
Define a PUT route
Route::patch('/users/{user}', [UserController::class, 'update'])
Define a PATCH route
Route::delete('/users/{user}', [UserController::class, 'destroy'])
Define a DELETE route
Route::get('/users/{id}', $fn)
Required route parameter
Route::get('/users/{id?}', $fn)
Optional route parameter
Route::get('/profile', $fn)->name('profile')
Name a route for URL generation
Route::get('/admin', $fn)->middleware('auth')
Attach middleware to a route
Route::resource('posts', PostController::class)
Register RESTful resource routes
Route::prefix('admin')->group(function () {})
Group routes under a URI prefix
Route::controller(PostController::class)->group($fn)
Group routes to one controller
Route::fallback($fn)
Handle unmatched routes (404)

Controllers

10
php artisan make:controller PostController --resource
Resource controller with CRUD methods
public function __invoke(Request $request)
Single-action invokable controller
public function index() {}
List resources (resource method)
public function store(Request $request) {}
Persist a new resource
public function show(Post $post) {}
Show one resource (route model binding)
public function __construct(PostService $svc) {}
Inject a dependency via the constructor
return view('posts.index', ['posts' => $posts])
Return a Blade view with data
return response()->json($data)
Return a JSON response
return redirect()->route('posts.index')
Redirect to a named route
return back()
Redirect to the previous page

Eloquent ORM

14
Post::all()
Get every record
Post::find($id)
Find a record by primary key
Post::where('active', true)->first()
First record matching a condition
Post::create(['title' => 'Hi'])
Mass-assign and persist a record
$post->update(['title' => 'Edited'])
Update an existing model
$post->delete()
Delete a model instance
Post::firstOrCreate(['slug' => $slug])
Find or create a matching record
Post::updateOrCreate($attrs, $values)
Update if found, otherwise create
Post::with('author')->get()
Eager load a relationship
public function comments() { return $this->hasMany(Comment::class); }
One-to-many relationship
public function author() { return $this->belongsTo(User::class); }
Inverse one-to-many relationship
protected $fillable = ['title', 'body'];
Mass-assignable attributes
protected function casts(): array { return ['published_at' => 'datetime']; }
Attribute casts (casts() method)
Post::onlyTrashed()->restore()
Restore soft-deleted records

Query builder

13
DB::table('users')->get()
Fetch all rows from a table
DB::table('users')->where('votes', '>', 100)->get()
Filter rows by a condition
DB::table('users')->join('posts', 'users.id', '=', 'posts.user_id')
Inner join two tables
DB::table('users')->orderBy('name')->get()
Order results by a column
DB::table('orders')->groupBy('status')->get()
Group rows by a column
DB::table('users')->select('name', 'email')->get()
Select specific columns
DB::table('users')->insert(['name' => 'Sam'])
Insert a new row
DB::table('users')->where('id', 1)->update(['votes' => 1])
Update matching rows
DB::table('users')->pluck('email')
Get a single column as a collection
DB::table('users')->count()
Count matching rows
DB::table('users')->where('id', 1)->exists()
Check whether rows exist
DB::table('users')->paginate(15)
Paginate the results
DB::table('users')->chunk(100, $fn)
Process results in chunks

Migrations & schema

12
Schema::create('posts', function (Blueprint $table) {})
Create a new table
$table->id()
Auto-incrementing primary key
$table->string('title')
VARCHAR column
$table->integer('votes')
Integer column
$table->boolean('active')
Boolean column
$table->timestamps()
created_at and updated_at columns
$table->foreignId('user_id')->constrained()
Foreign key with a constraint
$table->string('note')->nullable()
Allow NULL values
$table->boolean('active')->default(true)
Set a default value
$table->index('slug')
Add an index to a column
$table->unique('email')
Add a unique constraint
$table->dropColumn('votes')
Drop a column

Blade templates

14
@if ($ok) ... @elseif ($x) ... @else ... @endif
Conditional rendering
@foreach ($posts as $post) ... @endforeach
Loop over a collection
@forelse ($posts as $post) ... @empty ... @endforelse
Loop with an empty fallback
{{ $variable }}
Echo escaped output
{!! $html !!}
Echo unescaped raw HTML
@extends('layouts.app')
Inherit from a layout
@section('content') ... @endsection
Define a layout section
@yield('content')
Output a section in a layout
@include('partials.nav')
Include another view
<x-alert type="error" />
Render a Blade component
@csrf
CSRF token field for forms
@auth ... @endauth
Show content to authenticated users
@can('update', $post) ... @endcan
Authorization gate check
{{ $loop->index }}
Loop variable inside @foreach

Validation

12
$request->validate(['title' => 'required'])
Validate request data inline
'email' => 'required|email'
Required and valid email rule
'name' => 'required|max:255'
Required with a max length
'email' => 'unique:users,email'
Must be unique in a table
'age' => 'nullable|integer|min:18'
Optional integer with a minimum
'role' => ['required', Rule::in(['admin', 'user'])]
Constrain to allowed values
php artisan make:request StorePostRequest
Generate a Form Request class
public function rules(): array { return [...]; }
Form Request validation rules
public function authorize(): bool { return true; }
Form Request authorization
public function messages(): array { return [...]; }
Custom validation messages
$validator = Validator::make($data, $rules)
Create a validator manually
$request->validated()
Get only validated input

Requests & responses

10
request()->input('name')
Retrieve an input value
request()->query('page')
Retrieve a query string value
request()->all()
Get all input as an array
request()->only(['name', 'email'])
Get a subset of input
request()->has('name')
Check if input is present
response()->json(['ok' => true])
Return a JSON response
redirect()->route('home')->with('status', 'Saved')
Redirect with a flash message
back()->withInput()
Redirect back keeping old input
abort(404)
Throw an HTTP exception
abort_if($user->banned, 403)
Conditionally abort the request

Collections

13
$collection->map(fn ($x) => $x * 2)
Transform each item
$collection->filter(fn ($x) => $x > 0)
Keep matching items
$collection->each(fn ($x) => $x->save())
Run a callback per item
$collection->pluck('name')
Extract one column
$collection->reduce(fn ($c, $x) => $c + $x, 0)
Reduce to a single value
$collection->sortBy('created_at')
Sort by a key
$collection->groupBy('status')
Group items by a key
$collection->where('active', true)
Filter by a key/value pair
$collection->first()
Get the first item
$collection->contains('name', 'Sam')
Check for a matching item
$collection->sum('price')
Sum a column
$collection->flatten()
Flatten nested collections
$collection->toArray()
Convert to a plain array

Auth & middleware

11
Auth::user()
Get the authenticated user
Auth::check()
Check if a user is logged in
Auth::id()
Get the authenticated user ID
Auth::login($user)
Log a user in
Auth::logout()
Log the current user out
auth()->user()
Helper for the current user
Route::get('/home', $fn)->middleware('auth')
Protect a route with auth
Gate::allows('update', $post)
Check an authorization gate
$user->can('update', $post)
Check ability against a policy
php artisan make:policy PostPolicy --model=Post
Generate an authorization policy
php artisan make:middleware EnsureTokenIsValid
Generate a middleware class

Helpers & misc

12
config('app.name')
Read a config value
env('APP_DEBUG', false)
Read an environment variable
route('posts.show', $post)
Generate a URL to a named route
url('/dashboard')
Generate a fully qualified URL
asset('css/app.css')
URL for a public asset
old('email')
Retrieve old flashed input
now()->addDays(7)
Current Carbon timestamp
Str::slug('My Title')
String helper (slugify)
collect([1, 2, 3])->sum()
Create a collection from an array
cache()->remember('key', 60, $fn)
Cache a value for a duration
dd($value)
Dump a value and die
Storage::put('file.txt', $contents)
Write a file to storage

沒有條目符合「:q」。


關於 Laravel 速查表

這份 Laravel 速查表濃縮了你每天會接觸到的框架內容:Artisan 指令列、路由、控制器、Eloquent ORM、查詢建構器、資料庫遷移與結構、Blade 樣板、驗證、請求與回應、集合(Collections)、驗證與中介層,以及輔助函式。

Laravel 的 API 表達力強但範圍廣——確切的 Eloquent 關聯寫法、遷移欄位修飾詞、驗證規則名稱、集合方法等等,每一列都附上實際的呼叫方式與一行說明,讓這份速查表讀起來就像框架的速記版。

完全免費,且完全在瀏覽器端呈現。用搜尋框即時篩選每個程式碼片段,透過置頂目錄在各區段間跳轉,一鍵複製程式碼,還能列印下來當作建置時的框架參考。

如何使用 Laravel 速查表

  1. 瀏覽十二個區段,從「Artisan 指令列」「路由」一路到「Eloquent ORM」與「輔助工具與其他」。
  2. 搜尋像 migration、hasMany 或 validate 這類詞彙,即時篩選速查表。
  3. 透過置頂側邊欄跳轉到「Blade 樣板」或「集合」等區段。
  4. 點擊程式碼片段或其複製圖示,即可將 PHP 程式碼複製到你的專案中。
  5. 列印這份速查表,作為離線的 Laravel 參考。

常見問題

共十二個區段:Artisan 指令、路由、控制器、Eloquent、查詢建構器、資料庫遷移與結構、Blade、驗證、請求與回應、集合、驗證與中介層,以及一般輔助函式。

有。Artisan 區段列出你經常執行的產生器、遷移、快取與維護指令,每一項都附上簡短說明,說明它會產生或執行什麼。

有。Eloquent 區段展示模型定義、關聯與查詢寫法,另外還有獨立的查詢建構器區段,涵蓋你需要時可用的底層流暢式 API。

可以。點擊任何一列的程式碼或滑鼠懸停時出現的複製圖示,就會立即複製到剪貼簿。

是的,免費、可搜尋、可列印,無需帳號即可使用。


熱門搜尋
laravel cheat sheet artisan commands list eloquent query methods laravel routing syntax laravel validation rules blade directives list laravel migration schema methods laravel collections methods
需要協助?
使用此工具時遇到問題?請告訴我們的團隊。
回報問題

將此免費工具新增到你自己的網站 — 複製並貼上下面的程式碼。