Tài liệu tham khảo nhanh Laravel
Tài liệu tham khảo Laravel có thể tìm kiếm và in được — Artisan, routing, Eloquent, query builder, migration, Blade, xác thực và collection. Miễn phí.
Artisan CLI
14php artisan serve
Khởi động máy chủ phát triển cục bộ
php artisan make:model Post -mcr
Model kèm migration, controller và resource
php artisan make:controller PostController
Sinh một lớp controller mới
php artisan make:migration create_posts_table
Tạo một file migration mới
php artisan migrate
Chạy các migration cơ sở dữ liệu đang chờ
php artisan migrate:fresh --seed
Xóa mọi bảng, migrate lại và seed
php artisan db:seed
Chạy các seeder cơ sở dữ liệu
php artisan tinker
Mở một shell REPL tương tác
php artisan route:list
Liệt kê mọi route đã đăng ký
php artisan optimize
Cache config, route và view
php artisan queue:work
Xử lý job trên hàng đợi
php artisan schedule:work
Chạy scheduler ở tiền cảnh
php artisan storage:link
Tạo symlink storage tới đường dẫn public
php artisan key:generate
Sinh khóa ứng dụng
Định tuyến
13Route::get('/users', [UserController::class, 'index'])
Định nghĩa một route GET tới controller
Route::post('/users', [UserController::class, 'store'])
Định nghĩa một route POST
Route::put('/users/{user}', [UserController::class, 'update'])
Định nghĩa một route PUT
Route::patch('/users/{user}', [UserController::class, 'update'])
Định nghĩa một route PATCH
Route::delete('/users/{user}', [UserController::class, 'destroy'])
Định nghĩa một route DELETE
Route::get('/users/{id}', $fn)
Tham số route bắt buộc
Route::get('/users/{id?}', $fn)
Tham số route tùy chọn
Route::get('/profile', $fn)->name('profile')
Đặt tên route để sinh URL
Route::get('/admin', $fn)->middleware('auth')
Gắn middleware vào một route
Route::resource('posts', PostController::class)
Đăng ký route resource RESTful
Route::prefix('admin')->group(function () {})
Nhóm route dưới một tiền tố URI
Route::controller(PostController::class)->group($fn)
Nhóm route về một controller
Route::fallback($fn)
Xử lý route không khớp (404)
Controller
10php artisan make:controller PostController --resource
Controller resource với các method CRUD
public function __invoke(Request $request)
Controller invokable một hành động
public function index() {}
Liệt kê resource (method index)
public function store(Request $request) {}
Lưu một resource mới
public function show(Post $post) {}
Hiển thị một resource (route model binding)
public function __construct(PostService $svc) {}
Tiêm một phụ thuộc qua hàm khởi tạo
return view('posts.index', ['posts' => $posts])
Trả về một view Blade kèm dữ liệu
return response()->json($data)
Trả về một phản hồi JSON
return redirect()->route('posts.index')
Chuyển hướng tới một route có tên
return back()
Chuyển hướng về trang trước
Eloquent ORM
14Post::all()
Lấy mọi bản ghi
Post::find($id)
Tìm một bản ghi theo khóa chính
Post::where('active', true)->first()
Bản ghi đầu khớp một điều kiện
Post::create(['title' => 'Hi'])
Gán hàng loạt và lưu một bản ghi
$post->update(['title' => 'Edited'])
Cập nhật một model có sẵn
$post->delete()
Xóa một thực thể model
Post::firstOrCreate(['slug' => $slug])
Tìm hoặc tạo một bản ghi khớp
Post::updateOrCreate($attrs, $values)
Cập nhật nếu tìm thấy, nếu không thì tạo
Post::with('author')->get()
Eager load một quan hệ
public function comments() { return $this->hasMany(Comment::class); }
Quan hệ một-nhiều
public function author() { return $this->belongsTo(User::class); }
Quan hệ một-nhiều nghịch đảo
protected $fillable = ['title', 'body'];
Các thuộc tính gán được hàng loạt
protected function casts(): array { return ['published_at' => 'datetime']; }
Ép kiểu thuộc tính (method casts())
Post::onlyTrashed()->restore()
Khôi phục các bản ghi xóa mềm
Query builder
13DB::table('users')->get()
Lấy mọi hàng từ một bảng
DB::table('users')->where('votes', '>', 100)->get()
Lọc hàng theo một điều kiện
DB::table('users')->join('posts', 'users.id', '=', 'posts.user_id')
Inner join hai bảng
DB::table('users')->orderBy('name')->get()
Sắp xếp kết quả theo một cột
DB::table('orders')->groupBy('status')->get()
Nhóm hàng theo một cột
DB::table('users')->select('name', 'email')->get()
Chọn các cột cụ thể
DB::table('users')->insert(['name' => 'Sam'])
Chèn một hàng mới
DB::table('users')->where('id', 1)->update(['votes' => 1])
Cập nhật hàng khớp
DB::table('users')->pluck('email')
Lấy một cột đơn dưới dạng collection
DB::table('users')->count()
Đếm các hàng khớp
DB::table('users')->where('id', 1)->exists()
Kiểm tra hàng có tồn tại không
DB::table('users')->paginate(15)
Phân trang kết quả
DB::table('users')->chunk(100, $fn)
Xử lý kết quả theo khối
Migration & schema
12Schema::create('posts', function (Blueprint $table) {})
Tạo bảng mới
$table->id()
Khóa chính tự tăng
$table->string('title')
Cột VARCHAR
$table->integer('votes')
Cột số nguyên
$table->boolean('active')
Cột boolean
$table->timestamps()
Cột created_at và updated_at
$table->foreignId('user_id')->constrained()
Khóa ngoại kèm ràng buộc
$table->string('note')->nullable()
Cho phép giá trị NULL
$table->boolean('active')->default(true)
Đặt một giá trị mặc định
$table->index('slug')
Thêm một index cho một cột
$table->unique('email')
Thêm một ràng buộc unique
$table->dropColumn('votes')
Xóa một cột
Mẫu Blade
14@if ($ok) ... @elseif ($x) ... @else ... @endif
Render có điều kiện
@foreach ($posts as $post) ... @endforeach
Lặp qua một collection
@forelse ($posts as $post) ... @empty ... @endforelse
Lặp với nhánh dự phòng rỗng
{{ $variable }}
Xuất đầu ra đã thoát
{!! $html !!}
Xuất HTML thô chưa thoát
@extends('layouts.app')
Kế thừa từ một layout
@section('content') ... @endsection
Định nghĩa một section layout
@yield('content')
Xuất một section trong một layout
@include('partials.nav')
Include một view khác
<x-alert type="error" />
Render một thành phần Blade
@csrf
Trường token CSRF cho form
@auth ... @endauth
Hiển thị nội dung cho người dùng đã xác thực
@can('update', $post) ... @endcan
Kiểm tra gate phân quyền
{{ $loop->index }}
Biến vòng lặp trong @foreach
Xác thực
12$request->validate(['title' => 'required'])
Xác thực dữ liệu request nội tuyến
'email' => 'required|email'
Quy tắc bắt buộc và email hợp lệ
'name' => 'required|max:255'
Bắt buộc với độ dài tối đa
'email' => 'unique:users,email'
Phải là duy nhất trong một bảng
'age' => 'nullable|integer|min:18'
Số nguyên tùy chọn với giá trị tối thiểu
'role' => ['required', Rule::in(['admin', 'user'])]
Giới hạn ở các giá trị cho phép
php artisan make:request StorePostRequest
Sinh một lớp Form Request
public function rules(): array { return [...]; }
Quy tắc xác thực Form Request
public function authorize(): bool { return true; }
Phân quyền Form Request
public function messages(): array { return [...]; }
Thông điệp xác thực tùy chỉnh
$validator = Validator::make($data, $rules)
Tạo một validator thủ công
$request->validated()
Chỉ lấy đầu vào đã xác thực
Request & response
10request()->input('name')
Lấy một giá trị đầu vào
request()->query('page')
Lấy một giá trị query string
request()->all()
Lấy mọi đầu vào dưới dạng mảng
request()->only(['name', 'email'])
Lấy một tập con đầu vào
request()->has('name')
Kiểm tra đầu vào có hiện diện không
response()->json(['ok' => true])
Trả về một phản hồi JSON
redirect()->route('home')->with('status', 'Saved')
Chuyển hướng kèm một flash message
back()->withInput()
Chuyển hướng trở lại giữ đầu vào cũ
abort(404)
Ném một ngoại lệ HTTP
abort_if($user->banned, 403)
Hủy request có điều kiện
Collection
13$collection->map(fn ($x) => $x * 2)
Biến đổi mỗi mục
$collection->filter(fn ($x) => $x > 0)
Giữ các mục khớp
$collection->each(fn ($x) => $x->save())
Chạy một callback cho mỗi mục
$collection->pluck('name')
Trích một cột
$collection->reduce(fn ($c, $x) => $c + $x, 0)
Rút gọn về một giá trị
$collection->sortBy('created_at')
Sắp xếp theo một khóa
$collection->groupBy('status')
Nhóm các mục theo một khóa
$collection->where('active', true)
Lọc theo một cặp khóa/giá trị
$collection->first()
Lấy mục đầu tiên
$collection->contains('name', 'Sam')
Kiểm tra một mục khớp
$collection->sum('price')
Tính tổng một cột
$collection->flatten()
Làm phẳng các collection lồng nhau
$collection->toArray()
Chuyển thành một mảng thuần
Xác thực & middleware
11Auth::user()
Lấy người dùng đã xác thực
Auth::check()
Kiểm tra người dùng có đăng nhập không
Auth::id()
Lấy ID người dùng đã xác thực
Auth::login($user)
Đăng nhập một người dùng
Auth::logout()
Đăng xuất người dùng hiện tại
auth()->user()
Tiện ích cho người dùng hiện tại
Route::get('/home', $fn)->middleware('auth')
Bảo vệ một route bằng auth
Gate::allows('update', $post)
Kiểm tra một gate phân quyền
$user->can('update', $post)
Kiểm tra khả năng so với một policy
php artisan make:policy PostPolicy --model=Post
Sinh một policy phân quyền
php artisan make:middleware EnsureTokenIsValid
Sinh một lớp middleware
Tiện ích & khác
12config('app.name')
Đọc một giá trị config
env('APP_DEBUG', false)
Đọc một biến môi trường
route('posts.show', $post)
Sinh một URL tới một route có tên
url('/dashboard')
Sinh một URL đầy đủ
asset('css/app.css')
URL cho một asset công khai
old('email')
Lấy đầu vào cũ đã flash
now()->addDays(7)
Dấu thời gian Carbon hiện tại
Str::slug('My Title')
Tiện ích chuỗi (slugify)
collect([1, 2, 3])->sum()
Tạo một collection từ một mảng
cache()->remember('key', 60, $fn)
Cache một giá trị trong một khoảng thời gian
dd($value)
Xuất một giá trị và dừng
Storage::put('file.txt', $contents)
Ghi một file vào storage
Không có mục nào khớp với “:q”.
Cần trợ giúp?
Gặp sự cố với công cụ này? Hãy cho đội ngũ của chúng tôi biết.