Authorise actions with Gates (closures) and Policies (model-bound classes) in controllers and Blade.
Authorization
// Gate — simple closures
Gate::define("edit-post", function (User $user, Post $post) {
return $user->id === $post->user_id;
});
if (Gate::allows("edit-post", $post)) { /* ... */ }
Gate::authorize("edit-post", $post); // throws 403 if denied
// 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->isAdmin();
}
}
// In controller
$this->authorize("update", $post);
// In Blade
@can("update", $post)
<a href="{{ route("posts.edit", $post) }}">Edit</a>
@endcan