Middleware vs Gates/Policies
Both control access, but at different levels. Understand when to use each:
🛡️
Middleware - "Can this user make this TYPE of request?"
Before reaching controller, checking user STATUS
Is user logged in?
Route::get('/dashboard')->middleware('auth')
Middleware:
auth
Is email verified?
Route::get('/profile')->middleware('verified')
Middleware:
verified
Not rate-limited?
Route::get('/api/data')->middleware('throttle:60,1')
Middleware:
throttle:60,1
🔐
Policies - "Can this user act on THIS SPECIFIC resource?"
Inside controller, checking permissions on SPECIFIC MODEL
Can edit THIS post?
$this->authorize('update', $post);
Logic: Must be post author or admin
Can delete THIS comment?
$this->authorize('delete', $comment);
Logic: Must be comment owner
Can view THIS invoice?
$this->authorize('view', $invoice);
Logic: Must be invoice customer
🤔 What are you checking?
User status or capability
•
Logged in?
•
Verified email?
•
Has subscription?
Use Middleware
Permission on specific resource
•
Own this post?
•
Can edit this item?
•
Can delete this?
Use Gate/Policy
📝 Real-World Example: Blog Post Editing
1
User clicks "Edit Post"
Request: GET /posts/123/edit
2
Middleware checks: Is user logged in?
Route::middleware('auth')
If not logged in → redirect to login
3
Middleware checks: Is email verified?
Route::middleware('verified')
If not verified → redirect to verification page
4
Controller loads post, Policy checks: Can THIS user edit THIS post?
$this->authorize('update', $post)
Policy logic: User must be post author OR admin
5
All checks passed → Show edit form
✓ Success!
🎯 Key Takeaway
Middleware is your bouncer at the door - "Are you allowed in this club at all?" Policies are your table reservations - "Is this YOUR table specifically?" Use them together for complete access control!