A Simple Laravel ACL Example

Jordi Bassagañas
Nov 5 · 2 min read

Here are some goods news: Implementing an ACL (access control list) in your Laravel application is actually a snap.

Figure 1. A simple ACL describes how users are granted access to resources

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.

That’s it!

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.

Figure 2. Additional packages are not required on this occasion

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:

database/migrations/2019_11_04_161101_create_acls_table.php:

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:

app/Console/Commands/AclSetup.php:

Now, if running our shiny brand-new command:

php artisan acl:setup

The acls table will be seeded with the permissions data accordingly:

Finally we need to create the ACL middleware:

php artisan make:middleware Acl

app/Http/Middleware/Acl.php:

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 acls table.

Don’t forget to add the new middleware to the $routeMiddleware variable in your app/Http/Kernel.php file:

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.

You May Also Be Interested in…

Jordi Bassagañas

Written by

Hi there! How are you today? I blog about technology, the Internet, SEO, programming tips, PHP and many other things.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade