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() {}
列出资源(index 方法)
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 令牌字段
@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')
字符串辅助(生成 slug)
collect([1, 2, 3])->sum()
从数组创建集合
cache()->remember('key', 60, $fn)
缓存某值一段时间
dd($value)
转储值并终止
Storage::put('file.txt', $contents)
将文件写入存储
没有条目匹配“:q”。
需要帮助?
使用此工具时遇到问题?请告诉我们的团队。