Authorization in Laravel is the process of determining what an authenticated user is allowed to do in your application — for example, who can edit a post, delete a user, or access admin features.
👉 Authentication = “Who are you?”
👉 Authorization = “What are you allowed to do?”
Laravel Offers Two Authorization Methods:
1. Gates (Simple, Closures-Based)
Used for simple, single-action authorization logic.
2. Policies (Structured, Resource-Based)
Used for authorizing actions on Eloquent models (e.g., Post, User).
1. Gate Example
In AuthServiceProvider.php
:
use Illuminate\Support\Facades\Gate;
public function boot()
{
Gate::define('edit-post', function ($user, $post) {
return $user->id === $post->user_id;
});
}
Then use it in controller:
if (Gate::allows('edit-post', $post)) {
// User can edit
} else {
abort(403);
}
2. Policy Example
Step 1: Create a Policy
Put this comment in your project terminal:
php artisan make:policy PostPolicy --model=Post
Step 2: Define Methods
In app/Policies/PostPolicy.php
:
public function update(User $user, Post $post)
{
return $user->id === $post->user_id;
}
Step 3: Register Policy
In AuthServiceProvider.php
:
protected $policies = [
Post::class => PostPolicy::class,
];
Step 4: Use Policy
In Controller:
$this->authorize('update', $post);
Summary: Auth vs. Authorization
Feature | Purpose |
---|---|
Authentication | Identify the user |
Authorization | Decide what they can access/do |