An Introduction to Laravel Authorization Gates

Laravel Gate has an elegant mechanism to ensure users are authorized to perform actions on resources.

Before version 5.1, developers used ACL packages such as Entrust or Sentinel along with middlewares for authorization.
The problem with this approach is the permissions you attach to users are just flags; they don’t encode the complex logic of the permission for some use cases. We have to write the actual access logic within controllers.

Gate avoids some drawbacks of using just these mentioned packages:

Opinionated use case: Gate doesn’t define how you implement your models; it is up to you. This gives you the freedom to write all the complex specs your use case has however you like. You can even use ACL packages with Laravel Gate.
Defining logic(policy): Using Gate we can decouple access logic from business logic, which helps remove the clutter from controllers.

A Usage Example

In this post, we’ll make a toy posts app to show how Gate gives you liberty and decoupling.
The web app will have two user roles (authors and editors) with the following permissions:

  • Authors can create a post.
  • Authors can update their posts.
  • Editors can update any post.
  • Editors can publish posts.
It's only fair to share...Share on FacebookShare on Google+Tweet about this on TwitterShare on LinkedIn

Leave a Reply

Your email address will not be published. Required fields are marked *