Nâng CaoLaravel iconLaravel

Policy trong Laravel là gì và cách authorize action?

Policy tập trung hóa logic phân quyền. Tạo: php artisan make:policy PostPolicy --model=Post định nghĩa các method như view(), create(), update(), delete().

Ví dụ: public function update(User $user, Post $post) { return $user->id === $post->user_id; }. Dùng trong controller: $this->authorize("update", $post); hoặc inline if (auth()->user()->can("update", $post)).

Lợi ích: quy tắc auth tập trung, tái sử dụng qua nhiều controller, dễ test, dễ đọc. Laravel 11+: AuthServiceProvider đã bị xóa — đăng ký policy bằng Gate::policy() trong AppServiceProvider hoặc để auto-discovery tự động tìm.

Xem toàn bộ Laravel cùng filter theo level & chủ đề con.

Mở danh sách Laravel