Get Appointment

Blog Single

How to Use Laravel Role Permissions with Spatie Package | Step-by-Step Guide

  • Vfix Technology
  • 24 Sep 2024
  • Laravel
  • 1157 Views

In this tutorial, I’ll walk you through how to set up and use role-based permissions in Laravel using the Spatie role-permission package. Role-based access control is essential for managing user permissions in any modern web application. With Spatie's powerful package, you can easily assign roles and permissions to users, ensuring that only authorized users can access specific parts of your Laravel application. Let’s dive in and see how it’s done!

1. Install package:

composer require spatie/laravel-permission

2. Publish Config: 

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

3. Clear Config:

php artisan config:clear

4. Run the migration:

php artisan migrate

5. Add the necessary trait to your User model:

use Spatie\Permission\Traits\HasRoles;

use HasRoles;

6.  Register Middlware: In Laravel 11 open /bootstrap/app.php and register them there:

 $middleware->alias([
     'role' => \Spatie\Permission\Middleware\RoleMiddleware::class,
     'permission' => \Spatie\Permission\Middleware\PermissionMiddleware::class,
     'role_or_permission' => \Spatie\Permission\Middleware\RoleOrPermissionMiddleware::class,
 ]);

7.  Add Middlware on group routes: You can specify multiple roles or permissions with a | (pipe) character, which is treated as OR

Route::group(['middleware' => ['permission:create users|view users|edit users|delete users']], function () {
   Route::get('/add-user',function(){
    return "add user";
   });
});

8. Time to Create User Role & Permission Via CLI: 

php artisan permission:create-role admin web "create users|view users|edit users|delete users"

9. Let's Create One more role without permission for testing purpose only: 
When creating permissions/roles for specific guards you can specify the guard names as a second argument:

php artisan permission:create-role subscriber web

10. I am epxcing you would have installed laravel UI if not install it then - let's setup Register function to give a user role by default registration: 

protected function create(array $data)
{
        $user = User::create([
        'name' => $data['name'],
        'email' => $data['email'],
        'password' => Hash::make($data['password']),
    ]);

    $user->assignRole('subscriber');

    return $user;
}

11. Let's assign auth user as admin role for testing:

Route::get('/change-role', function () {
// only works if logged in
    $user = auth()->user();
    $user->assignRole('admin');
    $role = auth()->user()->getRoleNames()->first(); // Returns the first role

   // dd($role);
    return view('welcome');
});

12. Register New User and test new subscriber should not reach to :  ADD USER LINK. Only user role admin could access this route.

Some Examples:

Admin lte Sidebar Menu hide:

[
    'text' => 'pages',
    'url' => 'admin/pages',
    'icon' => 'far fa-fw fa-file',
    'label' => 4,
    'label_color' => 'success',
    'can' => 'create users | view users'
],

Some Blade Directive Examples:

@can('edit articles')
  //
@endcan
@if(auth()->user()->can('edit articles') && $some_other_condition)
  //
@endif
@role('writer')
    I am a writer!
@else
    I am not a writer...
@endrole

is the same as

@hasrole('writer')
    I am a writer!
@else
    I am not a writer...
@endhasrole
@if(auth()->user()->hasRole('writer'))
  //
@endif

Hope this tutorial helps you get started with implementing role-based permissions in your Laravel projects using the Spatie package. For more in-depth details and advanced features, make sure to check out the official Spatie documentation:
Link: https://spatie.be/docs/laravel-permission/v6/basic-usage/basic-usage



+91 8447 525 204 Request Estimate