Last reviewed: 24 Nov 2026
Our ERP's finance module started with one check: if ($user->is_admin). Then the client asked for accountants who can approve invoices but not delete them, a limit above which only the owner can approve, sales staff who see leads but never invoices, and a new billing screen that only some users should try first. We moved to roles and permissions with spatie/laravel-permission, and the first week was mostly 403 pages and exceptions. Ayesha, an accountant, got User does not have the right permissions. on a button she had every right to press, because a permission had been added straight into the database and the package was still serving its cached list.
This guide is the setup we use now, and the errors we hit on the way. I rebuilt it in a lab on the box (Laravel 13.43, spatie/laravel-permission 8.5, laravel/pennant 1.28, PHP 8.4, SQLite) with three users: Ayesha the accountant, Bilal from sales, and the owner as super admin. Every message below is real output from that lab.
The model in one minute
- Permissions are actions:
invoices.view,invoices.approve,leads.view. - Roles are job titles that bundle permissions: accountant, sales, super-admin.
- Policies add record-level rules, such as "only invoices up to 500,000".
- Feature flags (Pennant) decide whether a module exists for a user at all, which is a rollout decision, not a permission.
Code checks permissions, never role names. hasRole('accountant') in a controller breaks the day a second role needs the same access.
Setup
composer require spatie/laravel-permission
php artisan vendor:publish --provider="Spatie\Permission\PermissionServiceProvider"
php artisan migrateAdd the trait to the user model:
use Spatie\Permission\Traits\HasRoles;
class User extends Authenticatable
{
use HasFactory, Notifiable, HasRoles;
}Create permissions first, then roles, then assign them. A seeder that runs on every environment keeps them in sync:
foreach (['invoices.view', 'invoices.approve', 'invoices.delete', 'leads.view'] as $name) {
Permission::findOrCreate($name);
}
Role::findOrCreate('accountant')->syncPermissions(['invoices.view', 'invoices.approve']);
Role::findOrCreate('sales')->syncPermissions(['leads.view']);
Role::findOrCreate('super-admin');
$ayesha->assignRole('accountant');php artisan permission:show prints the matrix, which is the quickest way to answer "who can approve invoices?" (lab output after the cache example later in this post):
Guard: web
+------------------+------------+-------+-------------+
| | accountant | sales | super-admin |
+------------------+------------+-------+-------------+
| invoices.approve | ✔ | · | · |
| invoices.delete | · | · | · |
| invoices.view | ✔ | · | · |
| leads.view | · | ✔ | · |
| reports.export | ✔ | · | · |
+------------------+------------+-------+-------------+Errors and fixes, by cause
1. "There is no permission named ... for guard web"
Assigning a permission that has not been created yet throws, and so does a typo:
>>> $accountant->givePermissionTo('invoices.approve') // before the permission exists
Spatie\Permission\Exceptions\PermissionDoesNotExist: There is no permission named `invoices.approve` for guard `web`.
>>> User::find(2)->assignRole('acountant') // typo
Spatie\Permission\Exceptions\RoleDoesNotExist: There is no role named `acountant` for guard `web`.Fix: create permissions in the seeder before any role uses them (findOrCreate is safe to run again), and keep names in constants or an enum so typos fail in your editor instead of production.
Watch the difference between two checks. hasPermissionTo() throws for a permission that does not exist, while can() quietly returns false:
>>> User::find(1)->hasPermissionTo('reports.export') // never created
Spatie\Permission\Exceptions\PermissionDoesNotExist: There is no permission named `reports.export` for guard `web`.
>>> User::find(1)->can('reports.export')
=> falseA silent false is how a missing seeder turns into a "the button disappeared" ticket.
2. The guard does not match
Every role and permission has a guard_name. If you created them for web but the request authenticates through another guard, the lookup fails:
>>> Role::findByName('accountant', 'api')
Spatie\Permission\Exceptions\RoleDoesNotExist: There is no role named `accountant` for guard `api`.For a Sanctum-based SPA or mobile API, the user is still the same User model, so in most apps the simplest fix is to keep everything on the web guard. Only create a second set of roles for another guard when it really uses a different user provider.
3. "Target class [permission] does not exist"
The route middleware from the package is not registered automatically. Our first protected route returned a 500, and the log said:
$ curl -s -X POST -H 'Accept: application/json' http://127.0.0.1:8821/invoices/1/approve
{ "message": "Server Error" } [HTTP 500]
# storage/logs/laravel.log
local.ERROR: Target class [permission] does not exist.Register the aliases in bootstrap/app.php:
->withMiddleware(function (Middleware $middleware): void {
$middleware->alias([
'role' => \Spatie\Permission\Middleware\RoleMiddleware::class,
'permission' => \Spatie\Permission\Middleware\PermissionMiddleware::class,
'role_or_permission' => \Spatie\Permission\Middleware\RoleOrPermissionMiddleware::class,
]);
})The same error appears for any unregistered middleware or controller name; my Target class does not exist guide covers the other cases.
4. 403 "User does not have the right permissions."
With the alias in place, the route ->middleware(['auth', 'permission:invoices.approve']) behaves as intended:
# as Bilal (sales)
{ "message": "User does not have the right permissions." } [HTTP 403]
# as Ayesha (accountant)
{"invoice":"INV-1001","status":"approved"} [HTTP 200]If the right user gets this 403, check in this order: does the user have the role ($user->getRoleNames()), does the role have the permission (permission:show), is it the same guard, and is the cache stale (next section). For 403s that are not from permissions at all, such as a server rule or a missing policy, see my Laravel 403 Forbidden guide.
5. A permission added in the database is ignored
This was Ayesha's problem. The package caches roles and permissions (24 hours by default). Adding rows with raw SQL or DB::table() bypasses the code that clears that cache:
>>> User::find(1)->can('invoices.approve') // warms the permission cache
=> true
# a migration adds reports.export straight into the tables
>>> DB::table('permissions')->where('name','reports.export')->count()
=> 1
>>> User::find(1)->can('reports.export')
=> false
$ php artisan permission:cache-reset
Permission cache flushed.
>>> User::find(1)->can('reports.export')
=> trueCreate permissions through the package models (Permission::findOrCreate(), givePermissionTo()), which reset the cache for you, and add php artisan permission:cache-reset to the deploy script after migrations and seeders.
6. 403 "This action is unauthorized." from a policy
Permissions answer "can this person approve invoices?" Policies answer "can this person approve this invoice?" Ours adds the approval limit:
class InvoicePolicy
{
public function approve(User $user, Invoice $invoice): bool
{
return $user->can('invoices.approve') && $invoice->amount <= 500000;
}
}
// in the route or controller
Gate::authorize('approve', $invoice);Ayesha can approve INV-1001 (120,000) but not INV-1002 (900,000):
# INV-1002 = 900000
{ "message": "This action is unauthorized." } [HTTP 403]
# INV-1001 = 120000
{"invoice":"INV-1001","status":"approved"} [HTTP 200]Laravel finds App\Policies\InvoicePolicy for App\Models\Invoice by naming convention. If your policy lives elsewhere, register it with Gate::policy(), or every check returns false with this same message. When approvals have several levels, I move the limit into a workflow; my Laravel approval workflow guide shows that design.
7. The super admin is blocked too
We gave the owner a super-admin role with no permissions, expecting it to mean "everything". It does not, on its own:
# as owner, before Gate::before
{ "message": "User does not have the right permissions." } [HTTP 403]
{ "message": "This action is unauthorized." } [HTTP 403]Add a Gate::before in AppServiceProvider::boot(). Return null, not false, for everyone else so normal checks still run:
Gate::before(function ($user, $ability) {
return $user->hasRole('super-admin') ? true : null;
});After that, the owner got 200 on both the permission route and the 900,000 invoice. The package's permission: middleware goes through Laravel's gate, so the bypass covers it as well.
Feature access is not a permission
The new billing screen was a rollout, not an access rule, so we used Laravel Pennant instead of a temporary permission. Owner first, then individual users:
Feature::define('new-billing', fn (User $user) => $user->email === '[email protected]');
>>> Feature::for(User::find(3))->active('new-billing') // owner
=> true
>>> Feature::for(User::find(1))->active('new-billing') // Ayesha
=> false
>>> Feature::for(User::find(1))->activate('new-billing')
>>> Feature::for(User::find(1))->active('new-billing')
=> truePennant stored each decision in its features table (scope App\Models\User|1, value true), so a user does not flip between old and new screens. When the rollout ends, delete the flag; the permission list stays clean.
Common mistakes
- Checking role names in code instead of permissions.
- Hiding a button in React or Blade and leaving the API endpoint unprotected. The server must check every request.
- Adding permissions with raw SQL and forgetting
permission:cache-reset. - Forgetting to register the middleware aliases in
bootstrap/app.php. - Returning
falsefromGate::before, which denies everyone who is not super admin. - Using permissions as temporary on/off switches for beta modules.
Questions I get asked
Do I need the package, or are Gates and Policies enough?
For a few fixed rules, Laravel's Gates and Policies are enough. Once admins need to create roles and change permissions from a screen, a package that stores them in the database saves a lot of code.
How do I send permissions to a React or Next.js frontend?
Return $user->getAllPermissions()->pluck('name') with the logged-in user and use it to show or hide UI. Treat it as a display hint only; the API still checks on every request.
How do I handle permissions per company in a multi-tenant app?
The package has a teams mode that scopes roles to a team or tenant ID. Combine it with tenant scoping on your queries so one company never sees another company's records.
About the author. Muhammad Wilayat Shah is a senior full-stack engineer and team lead based in Islamabad, with 13+ years shipping ERP, HMS, school, fleet and property-portal products on Laravel, PHP, Node.js, React and PostgreSQL. His team's ERP finance module runs on the permission and policy split described here, and permission:cache-reset is a fixed step in their deploy script. More at wilayats.com/about.
Last reviewed: 24 Nov 2026




Comments
Join the discussion. Replies load on demand, up to 5 levels.
2 threads
Great explanation of Laravel RBAC! One of the biggest challenges in large ERP applications is managing permissions at both the route and feature levels. I really liked how this article separates roles, permissions, policies, and feature flags. Using Spatie for access control and Laravel Policies for record-level authorization is a practical approach.
One question: What's the best way to manage dynamic feature-level permissions, such as allowing users to view a page but restricting specific actions like exporting, editing, or approving records?
Really helpful and well-explained article! I like how you’ve covered roles, permissions, policies, and feature flags with practical examples. The troubleshooting tips for 403 errors and guard mismatches are especially useful for real-world Laravel projects. Great work!
Showing 1–2 of 2 threads