In this tutorial, you’ll learn how to use Laravel Policies and Gates to control access to specific actions (like edit, delete, and view) in your application.
We’ll continue from the Laravel 12 CRUD app with authentication you built earlier.
What Are Policies and Gates?
-
Gates: Define simple authorization logic using closures.
-
Policies: Group authorization logic for a specific model (like Post).
Example:
-
Only the post’s author can edit or delete their post.
-
All users can view posts.
Step 1 — Prerequisites
Make sure you have:
-
A working Laravel 12 CRUD app (from the previous tutorial)
-
Authentication enabled (
php artisan ui bootstrap --auth) -
A
poststable with auser_idcolumn (to track the post’s author)
Step 2 — Add user_id to the posts table
We’ll update the A posts table to store which user created each post.
Run migration command:
Edit the new migration file in database/migrations/:
Then migrate:
Step 3 — Update Post model
Open app/Models/Post.php and add the relationship to User:
Also ensure $fillable includes user_id:
Step 4 — Update the Controller to store the current user
In app/Http/Controllers/PostController.php, update your store() method:
Make sure your User model (app/Models/User.php) has this relationship:
Step 5 — Create a Policy for Post
Run this command:
This creates app/Policies/PostPolicy.php.
It includes default methods like view, update, delete, etc.
Step 6 — Define authorization rules
Open app/Policies/PostPolicy.php and edit it like this:
Only the author of the post can update or delete it.
Step 7 — Register the Policy
Open app/Providers/AuthServiceProvider.php and add this mapping:
Save the file.
Step 8 — Apply authorization in the controller
In PostController.php, add checks before update/delete:
Step 9 — Hide Edit/Delete Buttons in Views
Open resources/views/posts/index.blade.php
and wrap your buttons with @can directives:
Now, only the post owner sees these buttons.
Step 10 — Testing the Policy
-
Log in as User A
-
Create a post
-
Log out and log in as User B
-
Visit
/posts→ User B will not see edit/delete buttons for User A’s post -
If User B tries to access
/posts/1/editdirectly → Laravel will show a 403 Forbidden page
Policy is working successfully!
Summary
| Feature | Description |
|---|---|
| Gates | Simple authorization logic using closures |
| Policies | Organized authorization for specific models |
| @can / @cannot | Blade directives for UI control |
| authorize() | Controller method for enforcing rules |
You’ve Learned:
✔ How to create and register a Laravel Policy
✔ How to protect actions (edit, delete) by ownership
✔ How to show/hide UI based on permissions
✔ How to use Gates for simple cases
