Using Gates and Policies in Authorization Laravel

Tram Ho

Introduce :

Hello everyone, after working on a project, I have learned some interesting new things to share with everyone. Today, I am rising to let you talk a bit about Gates and Policies in Laravel

In addition to providing authentication services, Laravel also provides a simpler way to delegate user actions to a given resource. We have two ways of authorizing authorizations: gates and policies.

As stated in the document:

Gates:

Gates is a Closures that identifies users who are allowed to perform a certain action. We defined in the App Providers AuthServiceProvider class and use Illuminate Support Facades Gate. Gates always takes a user’s action as the first argument, we can customize it to receive additional arguments as an relevant Eloquent model:

When returning an authorization response from gates, Gate :: allows return to boolean values, if you want to customize the response yourself, you can use Gate :: inspect.

And finally, to use Gates, we use the following:

Policies:

As far as I understand, Policies is a class that manages authorizing logic. For example, I have a management page and only Admin or Pm can create a new project, then we have the corresponding Project and ProjectPolicy models to decentralize user actions such as creating or updating projects. .

Initializing Policies:

We can create Policies with the following command:

php artisan make: policy ProjectPolicy or attached with model php artisan make: policy ProjectPolicy –Project

Sign up for Polices:

After creating to register policies, we register in the App Providers AuthServiceProvider.php we have just created, for example:

And to set permissions for the user to create the project we register in the policies we just created:

Finally, the usage is very simple, in the controller we call the following: Gate :: authorize (‘view’, $ project);

End :

That’s a very simple use of Gates and Policies that I have used in my project, I’m happy to share them with everyone.

Share the news now

Source : Viblo