Overview
TheFilterRequestByRole middleware provides role-based field restriction for incoming requests. It acts as the first line of defense in the role-based field restriction pipeline, stripping or rejecting request fields that the authenticated user is not allowed to modify based on the $fieldsByRole configuration declared on the target Eloquent model.
This middleware must run after authentication middleware (
ctx.auth) so that auth()->user() is available, and before data.transform so the FormRequest never sees denied fields.Position in Pipeline
Constructor Parameters
This middleware is applied via route middleware and accepts parameters:Fully-qualified Eloquent model class name (e.g.,
App\Models\User)Filtering mode:
silent- Denied fields are silently removed (recommended for mobile/web)strict- Returns 403 error if denied fields are present (recommended for B2B/API partners)
Operating Modes
Silent Mode (Default)
Denied fields are silently removed from the request. The client receives no indication that the field was ignored.{"name": "John", "role": "admin"}, the role field is silently stripped before reaching the controller.
Strict Mode
If the client sends any denied field, returns a 403 error with field names.Model Integration
Your Eloquent model must implement thegetDeniedFieldsForUser() method:
Model Class Injection
This middleware automatically injects the resolved model class name as a request attribute:BaseRequest::mergeProhibitedRules() to auto-resolve the model without requiring child FormRequests to declare $modelClass, as long as role.filter is present in the route.
No-Op Conditions
The middleware passes through without filtering when:- HTTP verb is not
POST,PUT, orPATCH - No authenticated user (anonymous request)
- Model class does not exist
- Model does not implement
getDeniedFieldsForUser() getDeniedFieldsForUser()returns empty array (no restrictions / superuser)
Usage Examples
Basic Usage
With Controller Middleware
Combined with Other Middleware
Error Handling
Non-Production Environments
If the model class doesn’t exist, aRuntimeException is thrown to surface misconfiguration:
Production Environment
In production, the middleware fails open (lets the request through) to avoid blocking legitimate traffic due to configuration errors.Security Considerations
See Also
- TransformData Middleware - Data validation middleware
- SpatieAuthorize Middleware - Permission-based authorization
- InjectRequestParams Middleware - Request parameter injection