Оба инструмента для авторизации, но с разной областью применения.
Gate — простые одиночные проверки, не привязанные к модели:
// Определяем в AuthServiceProvider
Gate::define('access-admin-panel', function (User $user) {
return $user->is_admin;
});
// Проверяем
if (Gate::allows('access-admin-panel')) { ... }
// или в контроллере
$this->authorize('access-admin-panel');
Policy — класс с набором правил для конкретной модели:
// php artisan make:policy PostPolicy --model=Post
class PostPolicy
{
public function update(User $user, Post $post): bool
{
return $user->id === $post->user_id;
}
public function delete(User $user, Post $post): bool
{
return $user->id === $post->user_id || $user->is_admin;
}
}
// Использование
$this->authorize('update', $post);
Правило выбора
— Нет модели → Gate
— Есть модель, несколько действий → Policy