How to Implement User Role and Permission in Laravel 10?

15-Dec-2023

.

Admin

How to Implement User Role and Permission in Laravel 10?

Hello Dev,

This tutorial is focused on how to implement user roles and permissions in Laravel 10. This post will give you a simple example of how you assign permissions to a role in Laravel. let’s discuss how to set role permissions. you will learn how to assign users to permission sets. follow the below step for how to restrict users using permission sets.

To implement user roles and permissions in Laravel 10, follow these steps.

Install the Spatie Permission package.


composer require spatie/laravel-permission

Publish the package's configuration and migration files.

php artisan vendor:publish --provider="Spatie\Permission\PermissionServiceProvider"

Migrate the database.

php artisan migrate

Create the Role and Permission models.

php artisan make:model Role -m

php artisan make:model Permission -m

Update the User model to add the roles and permissions relationships.

<?php

namespace App\Models;

use Illuminate\Contracts\Auth\MustVerifyEmail;

use Illuminate\Database\Eloquent\Factories\HasFactory;

use Illuminate\Foundation\Auth\User as Authenticatable;

use Illuminate\Notifications\Notifiable;

use Laravel\Sanctum\HasApiTokens;

class User extends Model

{

use HasApiTokens, HasFactory, Notifiable;

/**

* The attributes that are mass assignable.

*

* @var array

*/

protected $fillable = [

'name',

'email',

'password',

];

/**

* The attributes that should be hidden for serialization.

*

* @var array

*/

protected $hidden = [

'password',

'remember_token',

];

/**

* The attributes that should be cast.

*

* @var array

*/

protected $casts = [

'email_verified_at' => 'datetime',

];

/**

* write code for.

*

* @param \Illuminate\Http\Request

* @return \Illuminate\Http\Response

* @author <>

*/

public function roles()

{

return $this->belongsToMany(Role::class);

}

/**

* write code for.

*

* @param \Illuminate\Http\Request

* @return \Illuminate\Http\Response

* @author <>

*/

public function permissions()

{

return $this->belongsToMany(Permission::class);

}

}

Create the Role and Permission seeders.

php artisan make:seeder RoleSeeder

php artisan make:seeder PermissionSeeder

In the RoleSeeder, create some roles and seed them into the database.

<?php

namespace Database\Seeders;

use Illuminate\Database\Console\Seeds\WithoutModelEvents;

use Illuminate\Database\Seeder;

use app/Models/Role;

class RoleSeeder extends Seeder

{

/**

* Run the database seeds.

*/

public function run()

{

$adminRole = Role::create(['name' => 'admin']);

$userRole = Role::create(['name' => 'user']);

$adminRole->givePermissionTo('all');

}

}

In the PermissionSeeder, create certain permissions and then seed them into the database.

<?php

namespace Database\Seeders;

use Illuminate\Database\Console\Seeds\WithoutModelEvents;

use Illuminate\Database\Seeder;

use app/Models/Permission;

class PermissionSeeder extends Seeder

{

/**

* Run the database seeds.

*/

public function run()

{

Permission::create(['name' => 'view users']);

Permission::create(['name' => 'create users']);

Permission::create(['name' => 'edit users']);

Permission::create(['name' => 'delete users']);

}

}

Run the seeders.

php artisan db:seed

Assign roles to users based on their responsibilities or access levels.

$user = User::find(1);

$user->assignRole('admin');

Verify whether a user possesses a specific role or permission.

$user = User::find(1);

if ($user->hasRole('admin')) {

// do something

}

if ($user->can('view users')) {

// do something

}

You can also employ middleware to safeguard your routes based on user roles. For instance, the following middleware will permit access to the /users route exclusively for users with the 'admin' role.

Route::middleware('role:admin')->get('/users', function () {

// ...

});

This serves as a fundamental tutorial on implementing user roles and permissions in Laravel 10. For more detailed information, please refer to the documentation for the Spatie Permission package.

I hope it can help you...

#Laravel 10