Overview
ThePermissionMiddleware class restricts access to routes based on user permissions. It checks if the authenticated user has at least one of the specified permissions before allowing the request to proceed.
Namespace: Spatie\Permission\Middleware\PermissionMiddleware
Registration
Register the middleware in yourbootstrap/app.php file:
Methods
handle()
Handles the incoming request and verifies the user has the required permission(s).$request- The incoming HTTP request$next- The next middleware closure$permission- Permission name(s) as string or pipe-separated values$guard- Optional authentication guard name
- Retrieves the authenticated user from the specified guard
- Supports Passport client credentials for machine-to-machine authentication
- Verifies the user has the
HasPermissionstrait - Checks if the user has any of the specified permissions (using pipe
|as separator) - Throws
UnauthorizedExceptionif user is not logged in, missing the trait, or lacks required permissions
UnauthorizedException::notLoggedIn()- User is not authenticatedUnauthorizedException::missingTraitHasRoles($user)- User model lacksHasRolestraitUnauthorizedException::forPermissions($permissions)- User lacks any of the required permissions
using()
Helper method to programmatically specify permissions and guard for the middleware.$permission- Permission name(s) as string, array, or BackedEnum$guard- Optional authentication guard name
Usage Examples
Single Permission
Protect a route requiring a single permission:Multiple Permissions (OR)
Allow access if user has ANY of the specified permissions:With Custom Guard
Specify a custom authentication guard:Using the using() Method
Programmatically specify permissions:Route Groups
Apply to multiple routes:With BackedEnum
Use PHP enums for type-safe permission definitions:Controller Usage
Apply in controller constructors:RESTful Resource Controllers
Protect all resource routes:Passport Client Credentials
The middleware supports Laravel Passport machine-to-machine authentication. Whenpermission.use_passport_client_credentials is enabled in config, the middleware will authenticate Passport clients using bearer tokens.
Combining with Other Middleware
You can combine permission middleware with other middleware:Notes
- The pipe character (
|) is used to separate multiple permissions, implementing OR logic - User must have at least ONE of the specified permissions to pass
- The middleware requires the user model to use the
HasRolestrait (which includes permissions) - For AND logic (requiring ALL permissions), chain multiple middleware calls
- Permissions are checked using the
canAny()method on the user model - The middleware checks for the
hasAnyPermission()method to verify the trait is present