A Simple Laravel ACL Example

Image for post
Image for post

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.

Image for post
Image for post
Figure 1. Additional packages are not required

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


As you can see for this to work it is important to define the following roles as constants in your app/User.php file:


Here comes the migration file.


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:


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


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.

You May Also Be Interested in…

Written by

Hi there! How are you today? I blog about technology, the Internet, SEO, programming tips, PHP and more. programarivm.com

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store