Managing Roles and Permissions in Laravel 12 with Spatie Laravel Permission

Learn how to set up role-based access control (RBAC) in Laravel 12 with the Spatie Laravel Permission package.


Introduction

Managing user roles and permissions is a key part of many applications. **Laravel** makes it easy to implement **role-based access control (RBAC)** using the **Spatie Laravel Permission** package. In this blog, we will walk you through how to set up roles and permissions in **Laravel 12** and use them to protect routes.


Step 1: Install Spatie Laravel Permission

To get started with roles and permissions, you first need to install the **Spatie Laravel Permission** package. Run the following command:

composer require spatie/laravel-permission

Once installed, publish the package’s configuration file and run the migrations to create the necessary tables:

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

Step 2: Configure Middleware in bootstrap/app.php

All route and middleware configuration occurs here in Laravel 12:


/* bootstrap/app.php */
use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Middleware;
use Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful;
use Spatie\Permission\Middleware\RoleMiddleware;
use Spatie\Permission\Middleware\PermissionMiddleware;
use Spatie\Permission\Middleware\RoleOrPermissionMiddleware;

return Application::configure(basePath: dirname(__DIR__))
    ->withRouting(
        commands: __DIR__.'/../routes/console.php',
        health: '/up',
        using: function () {
            // Web routes
            Route::middleware('web')
                 ->group(base_path('routes/web.php'));
            // API routes
            Route::middleware('api')
                 ->prefix('api')
                 ->name('api.')
                 ->group(base_path('routes/api.php'));
        }
    )
    ->withMiddleware(function (Middleware $middleware) {
        // Sanctum stateful middleware
        $middleware->prepend('api', EnsureFrontendRequestsAreStateful::class);
        // Spatie permission middleware aliases
        $middleware->alias([
            'role' => RoleMiddleware::class,
            'permission' => PermissionMiddleware::class,
            'role_or_permission' => RoleOrPermissionMiddleware::class,
        ]);
    })
    ->create();
    

Step 3: Set Up the User Model

To enable role and permission functionality in Laravel, add the **HasRoles** trait to your **User** model:


use Spatie\Permission\Traits\HasRoles;

class User extends Authenticatable
{
    use HasRoles;
}
        

Step 4: Define Roles and Permissions

Now, you’ll need to define your roles and permissions. You can do this by creating a **seeder** to insert them into the database:


// database/seeders/RolesAndPermissionsSeeder.php
namespace Database\Seeders;

use Illuminate\Database\Seeder;
use Spatie\Permission\Models\Role;
use Spatie\Permission\Models\Permission;

class RolesAndPermissionsSeeder extends Seeder
{
    public function run()
    {
        // Create permissions
        Permission::create(['name' => 'view users']);
        Permission::create(['name' => 'edit users']);
        Permission::create(['name' => 'delete users']);

        // Create roles
        $adminRole = Role::create(['name' => 'admin']);
        $userRole = Role::create(['name' => 'user']);

        // Assign permissions to roles
        $adminRole->givePermissionTo(Permission::all());
        $userRole->givePermissionTo('view users');
    }
}
        

Now, run the seeder to insert the roles and permissions into the database:

php artisan db:seed --class=RolesAndPermissionsSeeder

Step 5: Assign Roles and Permissions to Users

You can now assign roles and permissions to your users. To assign a role to a user:


$user = User::find(1);
$user->assignRole('admin');
        

Similarly, you can assign permissions to users:


$user->givePermissionTo('view users');
        

Step 6: Protect Routes with Middleware

Now that roles and permissions are set up, you can protect your routes using middleware. For example, if you want to restrict access to the **admin dashboard** to only users with the **admin** role, you can use the **role middleware**:


Route::middleware(['role:admin'])->get('/admin', function () {
    return view('admin.dashboard');
});
        

Conclusion

In this blog, we’ve walked through how to set up **role-based access control (RBAC)** using **Spatie’s Laravel Permission** package in **Laravel 12**. This package simplifies the process of managing user roles and permissions, making it easy to restrict access to routes based on roles and permissions. By following these steps, you can easily add robust role-based access control to your Laravel application.

apione.in

Comments

Leave a Reply