In this article, We are studying Policy in laravel. The policy helps developers streamline authorization logic and keep their code clean and maintainable. Laravel Policies provide a way to authorize user actions on resources. Policies help centralize authorization logic and make it easy to manage access rules.
How to make policy in laravel?
Create a Policy:
Run the below command, to create a policy class in laravel. It will create an ArticlePolicy class in the app\Policies directory.
php artisan make:policy ArticlePolicy
Define Policy Methods:
You can define different methods that perform on posts. You might create methods like view, create, update, and delete. These methods should return a boolean value.
public function view(User $user, Article $article)
{
return $user->id == $post->user_id;
}
The above method checks articles created by and access users is the same.
Register Policies:
You should register your policies in the AuthServiceProvider provider. You can add policies to their respective policies.
protected $policies = [
Article::class = ArticlePolicy::class,
];
Top comments (0)