Laravel Policies provide a convenient way to organize authorization logic around specific models. They act as classes that define methods to determine user permissions for performing actions on a resource.
Policies are part of Laravel's authorization system, introduced to simplify user permissions by encapsulating logic into reusable classes.
AuthServiceProvider
to register policies for models.Create a policy:
php artisan make:policy PostPolicy --model=Post
Define a policy method:
public function update(User $user, Post $post)
{
return $user->id === $post->user_id;
}
Register the policy in AuthServiceProvider
:
protected $policies = [
Post::class => PostPolicy::class,
];
Authorize an action in a controller:
$this->authorize('update', $post);
Laravel Policies centralize authorization logic, making applications more secure and maintainable.