😮 The Easiest Way to Create ACL for Laravel Projects.

Hujjat Nazari
May 24, 2018 · 3 min read
the easiest way to create ACL in Laravel.

When it comes to ACL (Access Control List ) we often find it so complicated 😕 by creating multiple roles and user_role tables and many to many relationships and so fourth. Well, let me show you the easiest way WITHOUT creating extra tables and relationships. 🙌

If you don’t know about ACL! it’s just the different user access level control. Think of a Content Management System, where you have admin who can do everything, author who can only create post and editor who can edit posts. ACL let you limit user permissions. THAT Simple 😵

So, let’s starts coding. 💻

Step 1.

Create a new field in your users table. (user_type)

User Type Field

Of course, migrate now :) 🏃

In this field, you store the user type (‘admin’, ‘author’,’editor’,’whatever’)

step 2.

Create a policy for users. open your ‘app/Providers/AuthServiceProvider.php’

Register User Type Policy in Laravel

Don’t forget to import GateContract at the top. 👇

Step 3

YOU ARE DONE !!!!!! 😊

Now, it’s the time to use them. 🏋

Usage in View files

In your Views, you may use the @canand @cannot family of directives.

You can use it to show or hide certain part of your view for different user type.

Only Admin Can see this menu items
Only Editors can see this menu items
Only Editors can see this menu items

Hope you got it. With just a little changes, you can adjust it for your project.

Usage in Controllers

Back-end is the important part. let’s see how you can limit access to Controller functions and logic.

Controller permission for user type of admin

That’s it 😍

Conclusion 🙇🏻

I hope it has been informative for you. Honestly, ACL can never be simpler than this. :). You wanna learn more about Laravel Authorization, check it in the documentation here. If you liked it article, give it a thumbs up, it’s free 😘

Hujjat Nazari

Written by

Self-taught Web Developer. I'm 18 years old with 5 years experience in web designing and development. I love coding with PHP, JavaScript, Laravel & Vuejs. react