Policy Classes in Laravel encapsulate authorization logic for specific models or resources. They provide a clean and organized way to define permissions and ensure your application enforces these rules consistently.
Policies were introduced as part of Laravel's authorization system to separate business logic from controllers, adhering to the Single Responsibility Principle.
php artisan make:policy
: Generate policy classes using Laravel's artisan command.AuthServiceProvider
.To create a policy for a Post
model:
php artisan make:policy PostPolicy
In PostPolicy
, define methods like:
public function update(User $user, Post $post)
{
return $user->id === $post->user_id;
}
Register the policy in AuthServiceProvider
:
protected $policies = [
Post::class => PostPolicy::class,
];
In a controller, use the policy:
$this->authorize('update', $post);
This approach ensures authorization rules are reusable and centralized.