User Roles and Permissions in Laravel

Photo by Alvaro Reyes on Unsplash

Sometimes an application has some restrictions for certain users or permissions of a feature for users who have certain roles. For example, let’s say there is a user who will act as Admin where he can do add new user but he can’t delete the user records and in other, there is a user who will act as Super Admin or anything else where he can do anything such as add new user or delete the user records. In this I will share about role and permission in Laravel using spatie package.

Install Spatie Package
Install spatie/laravel-permission package using this following command :

then you should publish the config file with :

after publish the config you can clear your config cache with :

then you can run the migrations for creating the tables of this pacakage using (don’t forget to setting your database in .env ):

Role and Permission
First you need to add the Spatie\Permission\Traits\HasRoles trait to your User model(s):

then we can create roles or permissions for our app, in this I will create a seeder for my new roles and it’s permissions.

in code above I assign the permission into a role, you can assign the permission directly into the user using something like this :

then you can run the seeder by following command :

and now the first user has SuperAdmin role and it has 2 permissions for write and delete a post, and the second user has Admin role with permission to write a post only.

Now we will able to do something like this :

or we can use the permission in views

or we can grouping our routes with permission like this

For example I will make the user with no edit-a-post permission can’t see the edit button and he will not be able to access the url directly.

Post views
Result if user access the url directly

Thats all that can I share about roles and permissions in Laravel, thanks for read my post and please feel free to leave a comment if you have any question or suggestion. Share if you find this post is useful. See ya…

Links To Project

Backend Developer | Laravel