Gates and Policies let you define authorization rules — who can do what — in a clean, reusable way.
// In a Service Provider boot() method
use Illuminate\Support\Facades\Gate;
Gate::define('edit-post', function (User $user, Post $post) {
return $user->id === $post->user_id;
});
// Using a gate
if (Gate::allows('edit-post', $post)) {
// Can edit
}
Gate::authorize('edit-post', $post); // Throws 403 if denied
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 a controller
public function update(Request $request, Post $post)
{
$this->authorize('update', $post);
// ...
}
// In Blade
@can('update', $post)
<a href="{{ route('posts.edit', $post) }}">Edit</a>
@endcan
@cannot('delete', $post)
<span>You cannot delete this post.</span>
@endcannot