DEV Community

Rohit Urane
Rohit Urane

Posted on

1 1 1 1

How to make policy in laravel?

Image description

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
Enter fullscreen mode Exit fullscreen mode

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;
}
Enter fullscreen mode Exit fullscreen mode

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,
];
Enter fullscreen mode Exit fullscreen mode

Read More

Heroku

Build apps, not infrastructure.

Dealing with servers, hardware, and infrastructure can take up your valuable time. Discover the benefits of Heroku, the PaaS of choice for developers since 2007.

Visit Site

Top comments (0)

Billboard image

Deploy and scale your apps on AWS and GCP with a world class developer experience

Coherence makes it easy to set up and maintain cloud infrastructure. Harness the extensibility, compliance and cost efficiency of the cloud.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay