Here are some goods news: Implementing an ACL (access control list) in your Laravel application is actually a snap.
Let me share a simple solution which basically consists in writing a middleware only to match the URL of the incoming request against the permissions stored into the database.
In the present article we are not using any third party Laravel package. Let’s say this simple ACL idea is an alternative for those who just don’t want to install additional dependencies.
For this reason it can also be used in plain PHP apps as well as in any other PHP framework — for example, Symfony.
By the way, the custom ACL is been implemented within the context of the Meerkat application which was introduced in the article entitled A Real-World React App (with Flux) for PHP Full-Stack Developers.
Let’s start by creating the
Acl model along with its corresponding migration file:
php artisan make:model Acl -m
Once you’re done with those two, don’t forget to recreate the database:
php artisan migrate:fresh
The next step is to write a handy Artisan command to easily set up the ACL from the command line as it is described next:
Now, if running our shiny brand-new command:
php artisan acl:setup
acls table will be seeded with the permissions data accordingly:
Finally we need to create the ACL middleware:
php artisan make:middleware Acl
Hopefully the middleware code should be self-explanatory, it basically reads the incoming route action along with the current user, matching the values obtained against the permissions stored into the
Don’t forget to add the new middleware to the
$routeMiddleware variable in your
By following the steps above, our middleware will be ready to be used in the API’s routes of the Meerkat app:
That’s all for now! I hope you enjoyed the example on how to implement a simple ACL in Laravel.
Remember, a third-party package is not actually necessary, so the main idea can be applied to any other PHP framework as well as to plain PHP apps.
Thank you so much for reading.