Laravel Role-Based Access Control (RBAC) System

Laravel Role-Based Access Control (RBAC) System

Introduction

Role-Based Access Control (RBAC) in Laravel allows you to assign roles and permissions to users, ensuring secure access to different parts of your application.

1. Installing Spatie Role Permission Package

To implement RBAC, install the Spatie Laravel Permission package:

composer require spatie/laravel-permission

2. Publishing Configuration and Running Migrations

Publish the package configuration:

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

Run the migrations:

php artisan migrate

3. Setting Up Models

Add the HasRoles trait to the User model:

use Spatie\Permission\Traits\HasRoles;

class User extends Authenticatable
{
    use HasRoles;
}

4. Creating Roles and Permissions

Use the Tinker console to create roles and permissions:

php artisan tinker

use Spatie\Permission\Models\Role;
use Spatie\Permission\Models\Permission;

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

$createPost = Permission::create(['name' => 'create post']);
$editPost = Permission::create(['name' => 'edit post']);
$deletePost = Permission::create(['name' => 'delete post']);

$admin->givePermissionTo([$createPost, $editPost, $deletePost]);
$editor->givePermissionTo([$createPost, $editPost]);
$viewer->givePermissionTo([]);

5. Assigning Roles to Users

Assign roles in a controller or seeder:

use App\Models\User;
use Spatie\Permission\Models\Role;

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

6. Checking Roles and Permissions

Check roles and permissions in controllers or middleware:

if (auth()->user()->hasRole('admin')) {
    return 'You are an admin';
}

if (auth()->user()->can('edit post')) {
    return 'You can edit posts';
}

7. Middleware for Role-Based Access

Add role-based middleware in Kernel.php:

'role' => \Spatie\Permission\Middlewares\RoleMiddleware::class,

Apply middleware to routes:

Route::group(['middleware' => ['role:admin']], function () {
    Route::get('/dashboard', function () {
        return 'Admin Dashboard';
    });
});

Conclusion

By implementing Role-Based Access Control (RBAC) in Laravel, you can manage user roles and permissions effectively, ensuring secure and structured access to your application.

© 2025 Developer Sahayak. All Rights Reserved.

0 Comments