Skip to content
Tutorials Center
My learning

Topics

Lesson 36 of 67 ยท Authentication and Authorization

Roles and Permissions Patterns

Design roles and permissions in Laravel: enum roles, role and permission pivot tables, permission checks in policies, team-scoped roles and when to use a package.

"Admins can do everything, editors can publish, readers can only read." Almost every application eventually needs rules like these, and the first question is always the same: where do they live? Laravel doesn't force a roles system on you, since gates and policies are the mechanism for answering "may this user do this?". What changes from project to project is the data model behind the answer.

This lesson walks the common designs from simplest to most flexible: a single enum column, several roles per user with a pivot table, roles that grant fine-grained permissions, roles that depend on a team, and finally the packages that package all of it up. Pick the simplest one that fits; each step adds tables, queries and things to test. The runnable examples are plain PHP stand-ins (the second runs on in-memory SQLite). The real Laravel code is shown read-only.

Pattern 1: one role per user, as an enum

If every user has exactly one role and the roles rarely change, a column on users is enough. A PHP backed enum keeps the values in one place and gives you autocompletion instead of magic strings:

PHP
namespace App\Enums;

enum Role: string
{
    case Admin = 'admin';
    case Editor = 'editor';
    case Reader = 'reader';

    public function canPublish(): bool
    {
        return match ($this) {
            self::Admin, self::Editor => true,
            self::Reader => false,
        };
    }
}

The migration stores the string, with a default for new users, and the model casts it to the enum (casts are covered in Accessors, Mutators and Casts):

PHP
$table->string('role')->default('reader');

// User model
protected function casts(): array
{
    return [
        'role' => Role::class,
    ];
}

Now $user->role === Role::Admin is a real comparison against a typed value, and an invalid role string in the database throws instead of silently passing. Policies use it directly:

PHP
public function publish(User $user, Post $post): bool
{
    return $user->role->canPublish();
}

This design is boring in a good way: no joins, trivial to test, easy to understand. Its limits are also clear. A user can't be both an editor and a billing manager, and adding a new role needs a code change and a deploy.

PHP Enum roles with a permission map

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Even with a single role you can already separate roles (who someone is) from permissions (what an action requires). Checking can(Permission::PublishPosts) in your code, instead of role === Editor, means that adding a "Moderator" role later changes the map, not every place that checks.

Pattern 2: many roles, a pivot table

When users can hold several roles, or administrators should create roles at runtime without a deploy, move roles into the database. A many-to-many relationship needs a pivot table, covered in Eloquent Relationships:

PHP
Schema::create('roles', function (Blueprint $table) {
    $table->id();
    $table->string('name')->unique();   // "editor"
    $table->timestamps();
});

Schema::create('role_user', function (Blueprint $table) {
    $table->foreignId('role_id')->constrained()->cascadeOnDelete();
    $table->foreignId('user_id')->constrained()->cascadeOnDelete();
    $table->primary(['role_id', 'user_id']);
});
PHP
// User model
public function roles(): BelongsToMany
{
    return $this->belongsToMany(Role::class);
}

public function hasRole(string $name): bool
{
    return $this->roles->contains('name', $name);
}

Because $this->roles loads the relation once and caches it on the model, repeated hasRole() calls in a request cost one query. Don't call $this->roles()->where(...)->exists() in a loop, or you will run a query per check; see Eager Loading and the N+1 Problem.

Pattern 3: roles grant permissions

Checking roles directly ("is this user an editor?") couples your code to role names. Checking permissions ("may this user publish?") is more stable: roles become named bundles of permissions that administrators can edit. That adds a second pivot, permission_role, and a third table, permissions.

erDiagram
    users ||--o{ role_user : has
    roles ||--o{ role_user : "assigned via"
    roles ||--o{ permission_role : grants
    permissions ||--o{ permission_role : "granted via"
    users {
        int id
        string name
    }
    roles {
        int id
        string name
    }
    permissions {
        int id
        string name
    }

Users hold roles, roles bundle permissions; the application code only ever asks about permissions.

A user's permissions are the union of the permissions of all their roles. The stand-in below builds exactly these five tables in SQLite and answers permission questions with one SQL join. It is a model of the idea, not Laravel's Eloquent; in an application you would express the same relationships on your models.

PHP A role and permission matrix on SQLite

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Ben shows the union at work: editor gives him publish and delete, billing adds invoices, and neither gives users.manage. Dev has no roles and so no permissions: deny by default is the right foundation. Production code would also give the roles table an administration screen and cache the permission lookup, since checks run on nearly every request (Caching).

Connecting permissions to Laravel's authorization

Don't create a second authorization system next to gates and policies. Instead, make the user model answer a permission question and let policies and the can helper use it:

PHP
// User model
public function hasPermission(string $permission): bool
{
    return $this->roles
        ->flatMap(fn (Role $role) => $role->permissions)
        ->contains('name', $permission);
}
PHP
// A policy that combines a permission with ownership
public function update(User $user, Post $post): bool
{
    return $user->hasPermission('posts.update.any')
        || ($user->hasPermission('posts.update.own') && $user->id === $post->user_id);
}

You can also register a gate for every permission name so @can('posts.publish') and $user->can('posts.publish') work without writing a policy for each. Roles say who you are; ownership ("this is my post") is a separate dimension that permissions alone can't express, which is why the policy above checks both. A global Gate::before for super admins (see Gates and Policies) belongs here too.

Pattern 4: team-scoped roles

In multi-tenant products a person is an admin of one team and a viewer in another. The role then lives on the relationship between user and team, so the pivot gets a third column:

PHP
Schema::create('team_user', function (Blueprint $table) {
    $table->foreignId('team_id')->constrained()->cascadeOnDelete();
    $table->foreignId('user_id')->constrained()->cascadeOnDelete();
    $table->string('role');                      // an enum value for this team
    $table->primary(['team_id', 'user_id']);
});
PHP
public function roleIn(Team $team): ?Role
{
    $membership = $this->teams->firstWhere('id', $team->id);

    return $membership ? Role::from($membership->pivot->role) : null;
}

Policies then receive the team (or the model's team) along with the user, and the question becomes "what is this user's role in this team?" Anything else, such as scoping queries so users only see their own team's records, is covered in Localization, Time Zones and Multi-Tenancy. The starter kits built around teams use this layout.

PHP Roles that depend on the team

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Ana can invite people into Team 1 and not into Team 2, though she is the same user. Cleo belongs to nothing and so can do nothing. Because the lookup returns null for strangers, the policy falls through to false.

Packages

Writing the tables, caching and administration screens yourself is educational, and for small apps often enough. For larger needs, packages implement the patterns above with caching and tooling:

  • spatie/laravel-permission is the most widely used. It adds roles and permissions tables, HasRoles on the model (assignRole(), hasRole(), givePermissionTo()), middleware, Blade directives, team support and cache handling, and it plugs into Laravel's can() checks.
  • Bouncer and similar packages offer an ability-based take with allow and forbid rules.
  • Filament Shield and other admin-panel add-ons build on top of those for generated screens.

Using a package is a good choice when you need runtime-editable roles, many permissions or team support. Using nothing but an enum is a good choice when you have three fixed roles. Check each package's current documentation for installation and Laravel 13 support before relying on it, and keep your application code asking permission questions (can('posts.publish')) so you can swap the backing implementation later.

Roles and permissions are only half of access control. Always authorize on the server (policies, middleware), deny by default, and remember that a user changing roles needs their cached permissions cleared.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. When is a single enum-cast role column on the users table a good fit?

    One column is the simplest design and works when roles are few, fixed and exclusive. Anything more flexible needs pivot tables.
  2. 2. Why check a permission (such as posts.publish) in code instead of a role name?

    Code that asks "may this user publish?" stays valid when role definitions change. Code that asks "is this user an editor?" has to be edited.
  3. 3. Which tables does the roles-grant-permissions design need for many-to-many on both sides?

    Users to roles and roles to permissions are each many-to-many, so each needs a pivot table in addition to the three entity tables.
  4. 4. Where does the role belong in a multi-tenant app where someone is an admin in one team and a viewer in another?

    The role describes the relationship between a user and a team, so it is stored on the pivot row for that pair.
  5. 5. What default is safest for a user who has no roles?

    Deny by default means access must be granted explicitly, so mistakes fail closed rather than open.

Summary

  • Gates and policies are the mechanism; roles and permissions are the data model behind them. Choose the simplest model that fits.
  • Enum role column: one role per user, cast to a backed enum; no joins, but not flexible.
  • Pivot tables (role_user) allow several roles per user; load the relation once ($user->roles) to avoid N+1 queries.
  • Permissions via roles (permission_role) let code ask "may this user do X?" and let administrators edit role definitions.
  • Combine permissions with ownership inside policies, and expose them to can() and @can.
  • Team roles live on the team_user pivot; packages such as spatie/laravel-permission implement these patterns with caching and tooling.
  • Deny by default, authorize on the server, and clear cached permissions when roles change.

Next: Queues and Jobs