Laravel 10 Authorization Policy Tutorial step by step | All about Laravel Policy
Laravel 10 Policy Tutorial step by step | All about Laravel Policy Tutorial
In this post, we will learn how to create a Laravel Policy and use Laravel Policy in our application.
What are Laravel Policies?
Laravel Policies provide a convenient way to authorize user actions on resources. These resources could be Eloquent models or any other objects in your application. Policies help centralize authorization logic and make it easy to manage access control rules. Instead of scattering authorization checks throughout your codebase, you can encapsulate them within dedicated policy classes.
Step 1: Create a Policy
You may generate a policy using the make:policy Artisan command
Suppose you would like to generate a class with example policy methods related to viewing, creating, updating, and deleting the resource. In that case, you may provide a --model option when executing the command:
Step 2: Registering Policies
You need to register your policies in the AuthServiceProvider. This class is located in the app/Providers directory.
In the AuthServiceProvider, you'll find a $policies property where you can map your models to their respective policies. For example:
Step 3: Define Policy Methods | Writing Policies
Inside the PostPolicy class, you can define methods that correspond to different actions users can perform on posts.
For example, you might create methods like view, create, update, and delete. These methods should return a Boolean value indicating whether the user is authorized to act. Here's an example of a methods in PostPolicy:
Open the PostPolicy.php file in path - app/ Policies/ PostPolicy.php
Policy Filters
For certain users, you may wish to authorize all actions within a given policy.
To accomplish this, define a "before" method on the policy. The before method will be executed before any other methods on the policy, giving you an opportunity to authorize the action before the intended policy method is actually called. This feature is most commonly used for authorizing application administrators to perform any action:
Step 4: Use Policies in Controllers
Open your PostController or any other controller as per your requirement and use the below code for the policy i.e. $this->authorize():
The authorize method checks if the current user is authorized to access the post using the all method defined in the PostPolicy.
Step 5: Use Policies in Blade Templates
@can is a shortcut of @if condition
@cannot is a shortcut of @unless condition
Instead of @can & @unless how can use in this way:
That's It.