Skip to main content

Overview

The SpatieAuthorize middleware provides centralized, convention-based authorization by automatically deriving required permissions from route metadata. It integrates with Spatie Laravel Permission and uses the in-memory permission cache for zero-database-hit authorization checks.
This middleware uses Spatie’s PermissionRegistrar for cache-aware permission lookups, ensuring high performance even with complex permission structures.

How It Works

The middleware derives required permissions from (in priority order):
  1. Route action overrides - Explicit permission definitions via ->defaults('authorize', [...])
  2. Route name conventions - Maps route names like articles.store to permissions
  3. Controller@method conventions - Derives from ArticleController@store
  4. HTTP verb + URI conventions - Last resort fallback

Constructor

PermissionRegistrar
required
Spatie’s permission registrar (automatically injected by Laravel)

Middleware Parameters

string
default:"config('auth.defaults.guard')"
Authentication guard to use (e.g., api, web)

Route Registration

Basic Usage

Custom Guard

Permission Resolution

Route Name Convention

The middleware maps standard resource route names to permissions:

Controller Method Convention

Derives permissions from controller and method names:
Mapping:

HTTP Verb Convention

Last resort: maps HTTP verb + first URI segment:

Explicit Route Overrides

Override automatic resolution with explicit permission requirements:

Single Permission

Multiple Permissions (OR)

Multiple Permissions (AND)

Pipe-Separated Syntax

Custom Guard Override

Guard Selection Priority

  1. Route override: ->defaults('authorize', ['guard' => 'api'])
  2. Middleware parameter: auto.authorize:api
  3. Application default: config('auth.defaults.guard')

Configuration Overrides

Create config/permission_map.php for additional customization:

Teams and Tenants

For multi-tenant applications using Spatie’s team support:
Register before auto.authorize:

Error Responses

Unauthorized Access

Debug Mode (app.debug = true)

Usage Examples

RESTful Resource

Mixed Automatic and Explicit

API with Custom Guard

Performance Notes

The middleware uses Spatie’s in-memory permission cache (PermissionRegistrar), resulting in zero database queries for permission checks after initial load.

Strict Mode

Enable strict mode to catch permission typos in development:
When enabled, the middleware will abort if a required permission doesn’t exist in the cache.

See Also