😮 The Easiest Way to Create ACL for Laravel Projects.
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)
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’
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 @can
and @cannot
family of directives.
You can use it to show or hide certain part of your view for different user type.
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.
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 😘