Hello Friends,
Gurpreet this side and in this article w,e will learn how to use roles and permissions in Laravel.
This is a package that allows you to set roles and permissions in your Laravel application which is provided by Spatie. For example: If you are building an application in which you have to manage multiple users like super-admin, admin, users, manager, etc. Then it is a good way to use the Laravel Permission package. Because It provides you an easy to use syntax to do desired functionality.
For Example, You can just use the “can” directive with that you can check if the user has particular permission then that will work according to the applied condition.
@can('manage posts')
<a href="#" class="btn btn-primary">Manage</a>
@endcan
So, Now the question is how to use this awesome package.
You can check this package on Spatie main Website Laravel-permission
How To Install Laravel Permission Package
So, let’s move on to the main discussion on how to install the package. First of all, set up your project with the database and then open your vs code command line.
composer require spatie/laravel-permission
This code will install this package and now you will have some other work to do. You have to register the service provider in config/app.php
so that it can run well.
'providers' => [
// ...
Spatie\Permission\PermissionServiceProvider::class,
];
Publish the migration file and before that, we would have a file in config/permission.php
so we also have to publish this and for this we have to run this command.
php artisan vendor:publish --provider="Spatie\Permission\PermissionServiceProvider"
php artisan:migrate
If you will get any error in this process as I have faced I got an error called: ” 1071 Specified key was too
long; max key length is 1000 bytes (SQL: alter table permissions
add unique permissions_name_guard_name_unique
(name
, guard_name
)) ” for this you can do one solution as I have used. Go to App directory in that App/Providers/AppServiceProvider.php
and add something like this.
public function boot()
{
Schema::defaultStringLength(125);
}
I hope this can help you there. By the way come back to the main topic.
After migration, you will have some tables in the database. See in the image below.
How to create roles and permissions
Now we will create a seeder if you don’t know what is seeder and how to use it. Let me tell you. We can create a seeder using php artisan make:seeder PermissionSeeder
it will create a seeding file in database/seeders/PermissionSeeder.
It already has a function called “run” in which you can just put whatever you want to seed into the database.
PermissionSeeder.php
class PermissionSeeder extends Seeder
{
/**
* Create the initial roles and permissions.
*
* @return void
*/
public function run()
{
// Reset cached roles and permissions
app()[PermissionRegistrar::class]->forgetCachedPermissions();
// create permissions
$permission1=Permission::create(['name' => 'SuperAdmin']);
$permission2=Permission::create(['name' => 'ServiceProvider']);
$permission3=Permission::create(['name' => 'BaseClient']);
// create roles and assign permissions
$role1 = Role::create(['name' => 'superadmin']);
$role1->givePermissionTo($permission1);
$role2 = Role::create(['name' => 'serviceprovider']);
$role2->givePermissionTo($permission2);
$role3 = Role::create(['name' => 'baseclient']);
$role3->givePermissionTo($permission3);
// gets all permissions via Gate::before rule; see AuthServiceProvider
}
}
Now after doing this you will have roles and permissions in your database which will look like this.
Permission Table
In roles you will have same data because I haven’t used permission by their abilities I have just put the name as in the roles table.
Now, We will also have a table in which it will be defined that which role has which permission and also which model has roles.
Now, take a look at modal_has_roles
table.
Now, we have setup everything. Let’s see the usage of roles and permissions
Usage Of Roles and Permissoin
For example, As I have explained in the above para that if you have multiple roles that can admin, super admin, manager or anything. Then we obviously needs to have some permissions so that we can maintain a relation between super admin and admin. So, that they can access their routes which they have assigned according to their roles.
How to assign Role to a User In Laravel Permission
Assigning role is not so complicated you should have to create role first in your db and for that you can use seeder as I have mentioned above and can do it easily. Now, let’s have a look at how to assign roles and permission when storing a user into database.
UserController Storing the user
public function store(StoreClientRequest $req)
{
$parentId = Auth::User()->id;
$parentName = Auth::User()->name;
$password = Hash::make($req->password);
$created = User::create($validatedData);
$created->assignRole(2) or assignRole('serviceprovider');
//this is how you can assign a role to a user
}
When you will be able to create user then you can add middleware’s also based on created roles. Let’s have a look at there how you can create middleware in <mark style="background-color:rgba(0, 0, 0, 0)" class="has-inline-color has-vivid-red-color">routes/web.php</mark>
.
Using Roles Middleware in Laravel Permission
If you don’t know about middleware then read about middleware Laravel-Middleware
We use middleware to protect routes. For example If you have assigned a middleware which a user middleware then you can’t get access into admin routes. Because you are out of that middleware.
Basically middleware is protecting wall by using this if you are into this wall then you can’t access those routes/url’s which are defined into middleware.
How to use middleware through roles
Route::group(['middleware' => 'role:serviceprovider'], function () {
//use any get or post route here.....
}
Route::group( ['middleware' => 'role:superadmin'], function () {
//use your superadmin routes here...
}
How to use blade directives in Laravel Permissione
This package provides you some blade directives which you can use for same purpose. For example: you have different pages in single sidebar some of them for admin and some of them for superadmin then you can use like this.
<ul>
<li> Admin page</li>
<li> Admin page</li>
<li> Admin page</li>
//then you can use @can directive here e.g
@can('manage everything')
<li> super admin page</li>
<li> super admin page</li>
@endcan
//it will check if logged in user has this permission then it will show these two pages to user.
</ul>
In the same way you can use other way also.
class PermissionSeeder extends Seeder
{
/**
* Create the initial roles and permissions.
*
* @return void
*/
public function run()
{
// Reset cached roles and permissions
app()[PermissionRegistrar::class]->forgetCachedPermissions();
// create permissions
$permission1=Permission::create(['name' => 'SuperAdmin']);
$permission2=Permission::create(['name' => 'ServiceProvider']);
$permission3=Permission::create(['name' => 'BaseClient']);
// create roles and assign permissions
$role1 = Role::create(['name' => 'superadmin']);
$role1->givePermissionTo($permission1);
$role2 = Role::create(['name' => 'serviceprovider']);
$role2->givePermissionTo($permission2);
$role3 = Role::create(['name' => 'baseclient']);
$role3->givePermissionTo($permission3);
// gets all permissions via Gate::before rule; see AuthServiceProvider
}
}
Same condition you can use by using role directive. Which will look like this.
@role('superadmin')
I am a superadmin!
@else
I am not a superadmin , I am else user or admin...
@endrole
Some other directives that you can use are listed below.
- @hasroles
- @hasanyroles
- @hasallroles
- @hasallroles
If you want to read more about this then you can move on to spatie package page – laravel-permissions(blade directives)
Conclusion
If we will see overall, it’s a great package to use without having any extra load about authentication you can just use this package to define roles and permission. In the very easiest way it will help you to define which role should have which permission. I hope this article will help you.
I have learned from this article/blog I hope you will also learn.
Thanks for reading ☺