A Simple Laravel ACL Example

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. This simple ACL idea is intended to those who are not big fans of installing unnecessary external dependencies in their projects.

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
app/Acl.php
:
As you can see for this to work it is important to define the following roles as constants in your app/User.php
file:
const CHOICE_ROLE_ADMIN = 'ROLE_ADMIN';
const CHOICE_ROLE_EDITOR = 'ROLE_EDITOR';
const CHOICE_ROLE_BASIC = 'ROLE_BASIC';
Here comes the migration file.
database/migrations/2019_11_04_161101_create_acls_table.php
:
Once you’re done with the above 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:
app/Console/Commands/AclSetup.php
:
Now, if running our shiny brand-new command the acls
table will be seeded with the permissions data accordingly:
php artisan acl:setup
Finally we need to write the ACL middleware:
php artisan make:middleware Acl
app/Http/Middleware/Acl.php
:
The middleware code is self-explanatory, it basically reads the incoming route action along with the current user, matching the values obtained against the permissions stored into the acls
table.
Remember to add the new middleware to the $routeMiddleware
variable in your app/Http/Kernel.php
file:
That’s all for now! By following the steps above, our ACL middleware is ready to be used in the routes/api.php
file:
I hope you enjoyed the example on how to implement a simple ACL in Laravel.
As said before, 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.