Laravel

Laravel Roles and Permissions with Spatie: Setup, Policies and Guard Gotchas

Authorization often starts as a few if ($user->is_admin) checks and grows into dozens of scattered, inconsistent conditions. Role-based access control (RBAC) replaces them with named permissions grouped into roles. Code asks "can this user edit articles?", and an administrator decides which roles carry that permission.

Laravel's Gates and Policies handle the "can this user do this?" question well, but they don't store roles and permissions in a database. The spatie/laravel-permission package adds that storage and plugs into Laravel's authorization, so $user->can(), @can and policies keep working as usual. This guide sets it up on Laravel 11+, shows where role checks and permission checks each belong, and covers the errors people most often hit.

Understanding RBAC Fundamentals

Before diving into the code, let's briefly clarify the core concepts:

  • Permissions: These are granular actions a user can perform. Examples include view posts, edit articles, delete users, publish reports. Think of them as individual capabilities.
  • Roles: These are collections of permissions. Instead of assigning dozens of individual permissions to each user, you assign them a role (or multiple roles). For example, an admin role might have view posts, edit articles, delete users, while an editor role might only have view posts and edit articles.

When someone's responsibilities change, you change their roles, and nothing in the code needs to change.

Setting Up Your Laravel Project and Spatie Permissions

First, ensure you have a fresh Laravel project set up. If not, you can create one with:

Bash
composer create-project laravel/laravel rbac-demo-app
cd rbac-demo-app

Now, let's integrate the spatie/laravel-permission package:

1. Install the Package via Composer

Add the package to your project using Composer:

Bash
composer require spatie/laravel-permission

2. Publish Migrations and Configuration

Next, publish the package's migration files and configuration file. This will add the necessary tables to your database to store roles and permissions.

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

This publishes config/permission.php and the migration.

3. Run Database Migrations

This creates the roles, permissions, role_has_permissions, model_has_roles and model_has_permissions tables.

Bash
php artisan migrate

4. Add the HasRoles Trait to Your User Model

Finally, modify your app/Models/User.php file to include the HasRoles trait. This trait provides all the necessary methods to interact with roles and permissions.

PHP
<?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;
use Spatie\Permission\Traits\HasRoles; // Import the trait

class User extends Authenticatable
{
    use HasApiTokens, HasFactory, Notifiable, HasRoles; // Use the trait

    // ... rest of your model ...
}

5. Know Which Guard You're Using

Every role and permission belongs to an auth guard (guard_name, default web). If your API authenticates with Sanctum, or your app uses a second guard such as admin, a permission created for web won't match a user authenticated by another guard. You'll see errors like There is no permission named edit articles for guard api, or checks that return false for no obvious reason. For a typical app with session and Sanctum authentication, keep everything on the web guard (Sanctum authenticates against it by default). Only create permissions for other guards when users really log in through a separate provider.

Defining and Assigning Roles and Permissions

Now that the groundwork is laid, let's define some roles and permissions.

1. Create Permissions

Define permissions and roles in a seeder, so every environment gets the same set and the seeder can be rerun safely. firstOrCreate makes it idempotent.

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

class RolesAndPermissionsSeeder extends Seeder
{
    public function run()
    {
        // The package caches permissions; clear it before changing them
        app()[PermissionRegistrar::class]->forgetCachedPermissions();

        // Create permissions
        Permission::firstOrCreate(['name' => 'view articles']);
        Permission::firstOrCreate(['name' => 'edit articles']);
        Permission::firstOrCreate(['name' => 'delete articles']);
        Permission::firstOrCreate(['name' => 'publish articles']);
        Permission::firstOrCreate(['name' => 'manage users']);

        // Create roles and assign existing permissions
        $adminRole = Role::firstOrCreate(['name' => 'admin']);
        $adminRole->givePermissionTo(Permission::all()); // Admins get all permissions

        $editorRole = Role::firstOrCreate(['name' => 'editor']);
        $editorRole->givePermissionTo(['view articles', 'edit articles', 'publish articles']);

        $viewerRole = Role::firstOrCreate(['name' => 'viewer']);
        $viewerRole->givePermissionTo('view articles');
    }
}

Remember to call this seeder from your main DatabaseSeeder.php:

PHP
// In DatabaseSeeder.php
$this->call(RolesAndPermissionsSeeder::class);

Run the seeder:

Bash
php artisan db:seed

2. Assign Roles to Users

Assign roles wherever users are created or managed, such as a registration action, an admin screen, or a factory in tests:

PHP
use App\Models\User;

// Example: Assigning roles to a user
$user = User::factory()->create(['email' => 'admin@example.com']);
$user->assignRole('admin');

$editor = User::factory()->create(['email' => 'editor@example.com']);
$editor->assignRole('editor');

$regularUser = User::factory()->create(['email' => 'user@example.com']);
$regularUser->assignRole('viewer');
// A user can also have multiple roles:
// $editor->assignRole(['editor', 'manager']);

// To remove a role:
// $user->removeRole('admin');

// To synchronize roles (replace all current roles with the given ones):
// $user->syncRoles(['editor', 'publisher']);

Checking Permissions and Roles

The HasRoles trait provides convenient methods for authorization checks.

1. In PHP Logic (Controllers, Services)

PHP
// Check if a user has a specific role
if (auth()->user()->hasRole('admin')) {
    // User is an admin
}

// Check a permission (preferred for authorizing actions)
if (auth()->user()->can('edit articles')) {
    // User can edit articles
}

// Check if a user has any of the given roles
if (auth()->user()->hasAnyRole(['admin', 'editor'])) {
    // User is either an admin or an editor
}

// In a controller, abort with 403 unless allowed
$this->authorize('edit articles');            // or Gate::authorize('edit articles')

can() works because the package registers every permission with Laravel's Gate. That's also why @can in Blade and can: route middleware recognize them.

2. In Blade Templates

Spatie provides Blade directives for easy checks in your views:

Blade
@role('admin')
    <a href="/admin/dashboard">Admin Dashboard</a>
@endrole

@hasanyrole('editor|admin')
    <p>You have editorial privileges!</p>
@endhasanyrole

@can('publish articles')
    <button>Publish Article</button>
@else
    <p>You don't have permission to publish.</p>
@endcan

3. Using Middleware

Register the package's middleware aliases in bootstrap/app.php (Laravel 11+). Note the namespace is Middleware (singular) in current versions of the package. Older tutorials use Middlewares, which no longer exists:

PHP
// bootstrap/app.php
->withMiddleware(function (Middleware $middleware) {
    $middleware->alias([
        'role' => \Spatie\Permission\Middleware\RoleMiddleware::class,
        'permission' => \Spatie\Permission\Middleware\PermissionMiddleware::class,
        'role_or_permission' => \Spatie\Permission\Middleware\RoleOrPermissionMiddleware::class,
    ]);
})

Then, apply it to your routes:

PHP
use App\Http\Controllers\ArticleController;
use Illuminate\Support\Facades\Route;

Route::middleware(['auth', 'role:admin'])->group(function () {
    Route::get('/admin/dashboard', function () {
        // Only accessible by users with the 'admin' role
    });
});

Route::middleware(['auth', 'permission:edit articles'])->group(function () {
    Route::get('/articles/{article}/edit', [ArticleController::class, 'edit']);
});

// For multiple roles/permissions (OR logic):
Route::middleware(['auth', 'role_or_permission:admin|editor'])->group(function () {
    // Accessible by users with 'admin' role OR 'editor' role
});

4. Leveraging Laravel Policies with Spatie

Permissions answer "can this user edit articles in general?". Many rules depend on the specific record: an author may edit their own drafts, an editor may edit any article. That logic belongs in a Policy, which combines permissions with ownership:

PHP
// app/Policies/ArticlePolicy.php

use App\Models\User;
use App\Models\Article;

class ArticlePolicy
{
    public function update(User $user, Article $article): bool
    {
        return $user->can('edit any article')
            || ($user->can('edit articles') && $user->id === $article->user_id);
    }
}

In the controller, $this->authorize('update', $article) runs this policy. For a super-admin who should pass every check, don't add hasRole('super-admin') to every policy. Register one Gate::before callback in AppServiceProvider::boot():

PHP
Gate::before(fn ($user, $ability) => $user->hasRole('super-admin') ? true : null);

Returning null (not false) for everyone else lets the normal checks run.

⚠️ Common mistake: Checking roles in application code (if ($user->hasRole('editor'))). The moment you need a "senior editor" or a "moderator" with some of the same abilities, every one of those checks must change. Check permissions in code, and decide which roles have which permissions in the seeder or an admin screen.

💡 Tip: Add a feature test per important permission: create a user with a given role and assert the expected 200 or 403 response. Permission changes then break tests instead of silently opening or closing access in production.

Summary

  1. Define permissions and roles in an idempotent seeder, and clear the permission cache when you change them.
  2. Check permissions in code (can(), @can, permission: middleware). Assign permissions to roles, and roles to users.
  3. Put record-specific rules in Policies, combining permissions with ownership checks.
  4. Handle super-admins once with Gate::before, not in every check.
  5. Keep roles and permissions on the guard your users actually authenticate with, usually web.
  6. Use the current middleware namespace (Spatie\Permission\Middleware) and register aliases in bootstrap/app.php.
Advertisement