How to use Laravel Permission Package
Tags: laravel, authentication
Published: 2022-08-25 07:14:06

---
title: How to use Laravel Permission Package
published: true
date: 2022-07-05 07:41:36 UTC
tags: Laravel,Authentication
canonical_url: https://larachamp.com/how-to-use-laravel-permission-package/
---

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.

![](https://larachamp.com/wp-content/uploads/2022/07/localhost-_-MySQL-_-roles_and_permissions-_-users-_-phpMyAdmin-5.1.1.png)
_roles and permissions tables_

## 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.

<mark style="background-color:rgba(0, 0, 0, 0)">PermissionSeeder.php</mark>

```
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.

<mark style="background-color:rgba(0, 0, 0, 0)">Permission Table</mark>

![](https://larachamp.com/wp-content/uploads/2022/07/localhost-_-MySQL-_-apkacfo-_-permissions-_-phpMyAdmin-5.1.1.png)
_table permission_

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.

![](https://larachamp.com/wp-content/uploads/2022/07/localhost-_-MySQL-_-apkacfo-_-roles-_-phpMyAdmin-5.1.1.png)
_table Roles_

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.

![](https://larachamp.com/wp-content/uploads/2022/07/localhost-_-MySQL-_-apkacfo-_-role_has_permissions-_-phpMyAdmin-5.1.1.png)
_Which role has which permission table – roles_has_permissions_

Now, take a look at `modal_has_roles` table.

![](https://larachamp.com/wp-content/uploads/2022/07/localhost-_-MySQL-_-apkacfo-_-model_has_roles-_-phpMyAdmin-5.1.1.png)
_table modal_has_roles_

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.

<mark style="background-color:rgba(0, 0, 0, 0)">UserController</mark> 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 `routes/web.php`.

## Using Roles Middleware in Laravel Permission

If you don’t know about middleware then read about middleware [Laravel-Middleware](https://laravel.com/docs/8.x/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.

```
@if(auth()->user()->can('edit articles') && $anyothercondition)
  //
@endif
```

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)](https://spatie.be/docs/laravel-permission/v5/basic-usage/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 ![☺](https://s.w.org/images/core/emoji/14.0.0/72x72/263a.png)

The post [How to use Laravel Permission Package](https://larachamp.com/how-to-use-laravel-permission-package/) first appeared on [larachamp.com](https://larachamp.com).

The post [How to use Laravel Permission Package](https://larachamp.com/how-to-use-laravel-permission-package/) appeared first on [larachamp.com](https://larachamp.com).