Guards and Policies in Laravel provide a robust system for managing authentication and authorization. Guards handle how users are authenticated, while Policies encapsulate the authorization logic for specific resources or actions.
Guards and Policies are part of Laravel's comprehensive authentication and authorization system, introduced to offer flexible, scalable solutions for user and resource management.
AuthServiceProvider
for seamless integration.Define a guard for API users in config/auth.php
:
'guards' => [
'api' => [
'driver' => 'token',
'provider' => 'users',
],
],
Create a policy for the Post
model:
php artisan make:policy PostPolicy
In the policy:
public function update(User $user, Post $post)
{
return $user->id === $post->user_id;
}
Register it in AuthServiceProvider
:
protected $policies = [
Post::class => PostPolicy::class,
];
Use the policy in a controller:
$this->authorize('update', $post);
This ensures secure and organized access control.