Last updated on October 18, 2026

Spatie Laravel Permission: Laravel 13 Guide

Arlind Musliu cofounder at Lucky Media
Arlind Musliu

February 12, 2025 · 8 min read

Laravel for Beginners Roles and Permissions with Spatie package

To add roles and permissions to a Laravel app, install the spatie/laravel-permission package, add the HasRoles trait to your User model, and give users roles that hold permissions. Then check access with Laravel's own can(), @can and can middleware, because the package plugs into Laravel's Gate.

This guide uses Laravel 13 and version 8 of the package. It covers install, seeding, middleware in bootstrap/app.php, Blade directives, a Super Admin, enums, teams, the permission cache, tests and the errors people hit most.

spatie/laravel-permission has more than 125 million installs on Packagist (October 2026), so it is the default choice for role-based access control (RBAC) in Laravel.

Which spatie/laravel-permission version works with Laravel 13?

Use version 7 or 8 for Laravel 12 and 13. Both need PHP 8.3 or higher. Version 6 still installs on Laravel 8 to 12, so older apps can stay on it. This table comes from the package's prerequisites page.

Laravel version

Package version

PHP

12, 13

^7.0 to ^8.0

8.3+

8, 9, 10, 11, 12

^6.0

8.0 to 8.5

7, 8, 9, 10

^5.8

7.3 to 8.3

Version 8.0.0 came out on May 30, 2026. The current release is 8.3.0. A plain composer require spatie/laravel-permission on a Laravel 13 app installs version 8.

What are roles and permissions?

Permissions

A permission is one action a user can take, such as "edit posts" or "delete posts". Your code checks permissions.

Roles

A role is a named group of permissions, such as "admin", "editor" or "user". You give roles to users, and the user gets every permission in the role.

The rule that keeps it simple

The Spatie docs give one rule that saves a lot of rework: users have roles, roles have permissions, and the app checks permissions. So write @can('edit posts'), not hasRole('editor'). Then you can rename a role or move a permission to another role without touching your controllers or views.

laravel best framework php

Do you need Spatie, or are Gates and Policies enough?

Laravel already has Gates and Policies for authorization. They answer "can this user do this to this record?" in code. Spatie adds a database layer on top, so admins can create roles and change permissions without a deploy.

Need

Gates and Policies

spatie/laravel-permission

Rules that depend on the record ("only the author can edit this post")

Yes

Use with a Policy

Roles and permissions stored in the database

No

Yes

Admin UI to change who can do what

You build it

Yes, with your own UI or Filament

Several roles per user

You build it

Yes

Roles scoped to a team or tenant

You build it

Yes, teams feature

Most apps use both. Spatie decides what a role may do, and a Policy decides which records that applies to. We cover Policies in Using Policies for Authorization and compare the two in Policies vs Roles and Permissions.

How to set up roles and permissions in Laravel 13

Step 1: Install the package

Require the package with Composer:

composer require spatie/laravel-permission

Publish the config file and the migration, clear the config cache, then run the migration:

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

The migration creates five tables: permissions, roles, model_has_permissions, model_has_roles and role_has_permissions. If you plan to use teams or UUIDs, change config/permission.php before you migrate. Laravel registers the service provider for you.

Building a Laravel app that needs roles and permissions?

Lucky Media builds custom backends for startups and enterprises. Let's talk

Step 2: Add the HasRoles trait to the User model

use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Spatie\Permission\Traits\HasRoles;

class User extends Authenticatable
{
    use HasRoles, Notifiable;

    // Your existing code...
}

The trait adds methods such as assignRole(), givePermissionTo(), hasRole() and getRoleNames(). Your User model must not have its own role, roles, permission or permissions column, property or relation, because they clash with the trait.

Step 3: Create roles and permissions in a seeder

Create a seeder:

php artisan make:seeder RolesAndPermissionsSeeder

Create permissions first, then roles, then link them. Reset the permission cache at the start so an old cache does not hide new records. findOrCreate() lets you run the seeder again without duplicate errors.

namespace Database\Seeders;

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(): void
    {
        // Reset cached roles and permissions
        app()[PermissionRegistrar::class]->forgetCachedPermissions();

        // Create permissions
        $viewPosts = Permission::findOrCreate('view posts');
        $editPosts = Permission::findOrCreate('edit posts');
        $deletePosts = Permission::findOrCreate('delete posts');

        // Create roles and give them permissions
        Role::findOrCreate('admin')->syncPermissions([$viewPosts, $editPosts, $deletePosts]);
        Role::findOrCreate('editor')->syncPermissions([$viewPosts, $editPosts]);
        Role::findOrCreate('user')->syncPermissions([$viewPosts]);
    }
}

Run it with php artisan db:seed --class=RolesAndPermissionsSeeder. For a quick test, you can also use the Artisan commands from the package:

php artisan permission:create-permission "edit posts"
php artisan permission:create-role editor web "view posts|edit posts"
php artisan permission:show

Step 4: Assign roles to users

$user = User::find(1);

$user->assignRole('editor');            // add a role
$user->syncRoles(['admin']);            // replace all roles with this list
$user->removeRole('admin');             // remove a role
$user->givePermissionTo('delete posts'); // direct permission, use rarely

$user->getRoleNames();                  // Collection: ['editor']
$user->getAllPermissions();             // permissions from roles + direct
User::role('editor')->get();            // all users with the editor role

To give roles to existing users in a seeder, call the seeder above first, then assign roles:

User::all()->each(function (User $user, int $index) {
    // First three users are admins, next three are editors, the rest are users
    $role = match (true) {
        $index < 3 => 'admin',
        $index < 6 => 'editor',
        default => 'user',
    };

    $user->assignRole($role);
});

Step 5: Check permissions in controllers

In Laravel 13 the base Controller class is empty, so $this->authorize() is not there by default. Use Gate::authorize() instead. It returns a 403 response when the check fails:

namespace App\Http\Controllers;

use App\Models\Post;
use App\Models\Tag;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Gate;

class PostController extends Controller
{
    public function show(Post $post)
    {
        Gate::authorize('view posts');

        return view('posts.show', ['post' => $post->load('user', 'tags')]);
    }

    public function edit(Post $post)
    {
        Gate::authorize('edit posts');

        return view('posts.edit', ['post' => $post, 'tags' => Tag::all()]);
    }

    public function update(Request $request, Post $post)
    {
        Gate::authorize('edit posts');

        $post->update($request->validate([
            'title' => 'required|max:255',
            'content' => 'required',
        ]));

        return redirect()->route('posts.show', $post);
    }

    public function destroy(Post $post)
    {
        Gate::authorize('delete posts');

        $post->delete();

        return redirect()->route('posts.index');
    }
}

If you prefer a redirect to a 403 page, check the user directly:

// Permission check (recommended): goes through Laravel's Gate
if ($request->user()->cannot('edit posts')) {
    return redirect()->route('posts.show', $post);
}

// Role check: works, but ties your code to role names
if (! $request->user()->hasRole(['admin', 'editor'])) {
    return redirect()->route('posts.show', $post);
}

Step 6: Register the middleware and protect routes

Since Laravel 11 there is no app/Http/Kernel.php. Register the package middleware aliases in bootstrap/app.php:

use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Middleware;
use Spatie\Permission\Middleware\PermissionMiddleware;
use Spatie\Permission\Middleware\RoleMiddleware;
use Spatie\Permission\Middleware\RoleOrPermissionMiddleware;

return Application::configure(basePath: dirname(__DIR__))
    // ...
    ->withMiddleware(function (Middleware $middleware) {
        $middleware->alias([
            'role' => RoleMiddleware::class,
            'permission' => PermissionMiddleware::class,
            'role_or_permission' => RoleOrPermissionMiddleware::class,
        ]);
    })
    // ...

Then use the aliases on routes. A pipe | means OR:

Route::middleware('role:admin')->group(function () {
    Route::get('/admin', AdminDashboardController::class);
});

Route::middleware('permission:edit posts')
    ->get('/posts/{post}/edit', [PostController::class, 'edit']);

Route::middleware('role:admin|editor')
    ->get('/drafts', DraftController::class);

// Laravel's built-in can middleware also works, with no alias needed
Route::middleware('can:delete posts')
    ->delete('/posts/{post}', [PostController::class, 'destroy']);

When the check fails, the package throws Spatie\Permission\Exceptions\UnauthorizedException, and Laravel returns a 403.

Using Laravel Pipelines

Step 7: Show or hide content in Blade

Use Laravel's @can and @canany for permissions. The package adds @role, @hasanyrole and @hasallroles for the rare case where you must check a role:

@can('edit posts')
    <a href="{{ route('posts.edit', $post) }}">Edit</a>
@endcan

@canany(['edit posts', 'delete posts'])
    <x-post-actions :post="$post" />
@endcanany

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

@hasanyrole('admin|editor')
    <a href="/drafts">Drafts</a>
@endhasanyrole

Step 8: Add a Super Admin with Gate::before

Do not give a Super Admin every permission one by one. Add a Gate::before rule in AppServiceProvider instead:

use Illuminate\Support\Facades\Gate;

public function boot(): void
{
    Gate::before(function ($user, $ability) {
        return $user->hasRole('Super Admin') ? true : null;
    });
}

Return null, not false, so normal checks still run for other users. This rule only applies to Gate checks such as can(), @can and Gate::authorize(). A direct call to hasPermissionTo() skips the Gate.

Use enums for role and permission names

Typos in permission strings fail without a clear error. A backed enum gives you autocomplete and one place to change a name. Version 8 accepts a BackedEnum in findByName() and findOrCreate(), as well as in assignRole(), givePermissionTo() and hasPermissionTo():

namespace App\Enums;

enum PostPermission: string
{
    case View = 'view posts';
    case Edit = 'edit posts';
    case Delete = 'delete posts';
}

// Usage
Permission::findOrCreate(PostPermission::Edit);
$role->givePermissionTo(PostPermission::Edit);
$user->hasPermissionTo(PostPermission::Edit);

// Gate checks and Blade need the string value
$user->can(PostPermission::Edit->value);
@can(enum_value(PostPermission::Edit))

Teams: roles per company or tenant

In a SaaS app, a user can be an admin in one company and a viewer in another. The teams feature handles this. Turn it on in config/permission.php before you run the migration:

'teams' => true,

If you already migrated, run php artisan permission:setup-teams and then php artisan migrate. On each request, set the current team in a middleware with setPermissionsTeamId($teamId). Every role check after that is scoped to that team. Read the teams docs for the middleware priority step, because a wrong order gives a 404 where you expect a 403.

The permission cache: when to reset it

The package caches roles and permissions for 24 hours by default. Its own methods, such as givePermissionTo() and Role::create(), reset the cache for you. You must reset it yourself when you change the tables directly with SQL or a query builder:

php artisan permission:cache-reset

If you use CACHE_STORE=database, create Laravel's cache table first. Without it, you get errors such as Call to a member function perform() on null.

Test roles and permissions

A short feature test catches a missing permission before your users do. This example uses Pest:

use App\Models\Post;
use App\Models\User;
use Database\Seeders\RolesAndPermissionsSeeder;

beforeEach(fn () => $this->seed(RolesAndPermissionsSeeder::class));

it('lets an admin delete a post', function () {
    $admin = User::factory()->create()->assignRole('admin');
    $post = Post::factory()->create();

    $this->actingAs($admin)
        ->delete(route('posts.destroy', $post))
        ->assertRedirect(route('posts.index'));
});

it('stops an editor from deleting a post', function () {
    $editor = User::factory()->create()->assignRole('editor');
    $post = Post::factory()->create();

    $this->actingAs($editor)
        ->delete(route('posts.destroy', $post))
        ->assertForbidden();
});

Common errors and how to fix them

Error

Cause

Fix

Target class [role] does not exist.

The middleware alias is not registered.

Add the aliases in bootstrap/app.php (Step 6).

There is no role named `admin` for guard `web`.

The role is not in the database, has another guard, or the cache is old.

Run the seeder, check guard_name, then run php artisan permission:cache-reset.

Trait "Spatie\Permission\Traits\HasRoles" not found

The package is not installed in this environment.

Run composer require spatie/laravel-permission, then composer dump-autoload.

1071 Specified key was too long

MySQL index length limit with utf8mb4.

Use InnoDB with the Dynamic row format, or set Schema::defaultStringLength(125).

A 404 where you expect a 403

Route model binding runs before the permission middleware.

Run the package middleware before SubstituteBindings.

Upgrading from version 6 to version 8

Upgrade Laravel to 12 or 13 and PHP to 8.3 first. Then set "spatie/laravel-permission": "^8.0" and run composer update spatie/laravel-permission. Check these breaking changes from the upgrade guide:

  • Event classes now end in Event, for example RoleAttachedEvent. Update your listeners.

  • Command classes now end in Command. The Artisan command names do not change.

  • assignRole(), syncRoles() and givePermissionTo() now return static. Update any method you override.

  • In version 8, the Role and Permission contracts accept BackedEnum|string in findByName() and findOrCreate(). Update custom models that implement them.

  • Lumen support is gone.

FAQs

What is Spatie in Laravel?

Spatie is a web agency in Antwerp, Belgium that publishes many open source Laravel packages. When developers say "Spatie permissions", they mean spatie/laravel-permission, the package that stores roles and permissions in the database and connects them to Laravel's Gate.

Does spatie/laravel-permission support Laravel 13?

Yes. Versions 7 and 8 support Laravel 12 and 13 and need PHP 8.3 or higher. Version 8 is the current major version, and Composer installs it by default on a new Laravel 13 app.

How do I get a user's roles with Spatie?

Call $user->getRoleNames() to get a collection of role names, or $user->roles to get the Role models. Use $user->getAllPermissions() to get every permission the user has from roles and direct grants.

How do I clear the Spatie permission cache?

Run php artisan permission:cache-reset, or call app()[PermissionRegistrar::class]->forgetCachedPermissions() in code. You only need this after you change the permission tables without the package methods, or at the start of a seeder.

Should I check roles or permissions in Laravel?

Check permissions. Give permissions to roles and roles to users, then use can(), @can and the can middleware in your code. This lets you change roles later without code changes.

Is Spatie better than Laravel Gates and Policies?

They do different jobs. Gates and Policies hold authorization rules in code, often per record. Spatie stores roles and permissions in the database so admins can change them, and it works through the same Gate, so most apps use both.

More Laravel authorization guides

This article is part of our series Laravel for Beginners: A Step-by-Step Guide to Learn the Concepts.


Bring Your Ideas to Life 🚀

If you need help with a Laravel project, get in touch. Our Laravel team builds admin panels, APIs and access control for startups and enterprise teams.

Lucky Media is proud to be recognized as a leading Laravel Development Agency

Technologies

Laravel
Arlind Musliu cofounder at Lucky Media
Arlind Musliu

Cofounder and CFO of Lucky Media

Stay up-to-date

Be updated with all news, products and tips we share!

Let’s chat

We partner with a limited number of brands each quarter to ensure senior-level attention on every project.

Teamwork