Overview
TheRoleMiddleware class restricts access to routes based on user roles. It checks if the authenticated user has at least one of the specified roles before allowing the request to proceed.
Namespace: Spatie\Permission\Middleware\RoleMiddleware
Registration
Register the middleware in yourbootstrap/app.php file:
Methods
handle()
Handles the incoming request and verifies the user has the required role(s).$request- The incoming HTTP request$next- The next middleware closure$role- Role 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
HasRolestrait - Checks if the user has any of the specified roles (using pipe
|as separator) - Throws
UnauthorizedExceptionif user is not logged in, missing the trait, or lacks required roles
UnauthorizedException::notLoggedIn()- User is not authenticatedUnauthorizedException::missingTraitHasRoles($user)- User model lacksHasRolestraitUnauthorizedException::forRoles($roles)- User lacks any of the required roles
using()
Helper method to programmatically specify roles and guard for the middleware.$role- Role name(s) as string, array, or BackedEnum$guard- Optional authentication guard name
Usage Examples
Single Role
Protect a route requiring a single role:Multiple Roles (OR)
Allow access if user has ANY of the specified roles:With Custom Guard
Specify a custom authentication guard:Using the using() Method
Programmatically specify roles:Route Groups
Apply to multiple routes:With BackedEnum
Use PHP enums for type-safe role definitions:Controller Usage
Apply in controller constructors: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.
Notes
- The pipe character (
|) is used to separate multiple roles, implementing OR logic - User must have at least ONE of the specified roles to pass
- The middleware requires the user model to use the
HasRolestrait - For AND logic (requiring ALL roles), chain multiple middleware calls
- Roles are checked using the
hasAnyRole()method on the user model