Laravel Policy vs Gate — Authorization with Syntax Examples
Authentication vs Authorization:
Authentication confirms who the user is (login with email/password).
Authorization determines what that user can do (edit posts, delete users, etc.).
Laravel handles both using guards, middleware, gates, and policies.
In Laravel, authorization logic is handled using Policies and Gates. Both allow you to control access to actions like update, delete, or view. Here's a comparison with syntax and use cases.
Step 1: Use Gates for simple, closure-based checks — usually used in small apps or single-condition logic.Step 2: Use Policies for model-based authorization — useful in larger applications with reusable logic.
Step 3: Create a Gate inside
AuthServiceProvider using closure syntax:Gate::define('delete-post', function ($user, $post) { return $user->id === $post->user_id; });Step 4: Use a Gate in Blade view like this:
@can('delete-post', $post) <button>Delete</button> @endcanStep 5: Create a Policy via artisan:
php artisan make:policy PostPolicy --model=PostStep 6: Define methods in your policy like
update or delete and compare user permissions:public function update(User $user, Post $post) { return $user->id === $post->user_id; }Step 7: Register the policy in
AuthServiceProvider:protected $policies = [Post::class => PostPolicy::class];Step 8: Use policy in controller like:
$this->authorize('update', $post);Step 9: You can also use policy in Blade view:
@can('update', $post) <button>Edit</button> @endcanStep 10: Gates are best when authorization is not tied to a model. Policies are better when dealing with model resources.
Step 11: Laravel automatically maps policy methods based on resource controller methods like
show, update, etc.Step 12: Always run
php artisan make:policy with --model flag to bind to a model directly.Step 13: Combine policies with middleware like
can:update,post to secure routes.Step 14: Gates are quick, while Policies offer organized, scalable authorization logic for large apps.
Step 15: Final recommendation: Use Policies for resources (CRUD apps) and Gates for standalone logic (admin-only sections, roles).