How it Works
The middleware intercepts the request before it reaches the controller and performs the following steps:- Extract Runtime Documentation: It retrieves the merged documentation from
$request->getRuntimeDocumentation()— the developer-declared properties plus route-derived metadata (filters, pagination params, available sort fields). - Property Validation: It iterates Body, Query, and Path properties and checks each corresponding value in the
ParameterBag— running all validators attached to the property (StringValidator,IntegerValidator,EnumValidator, …). - Required Field Check: If a property is marked
requiredbut missing, a validation error is recorded. - Filter Validation: Each filter in
$request->filtering()is validated against its underlying property (required / type / custom validators). - Sort Field Validation: Each
Sortin$request->sorting()must correspond to a field declared on the route viaRoute::sorting([...]). Unknown fields sent via?order_by=...produce a validation error (keyorder_by, messageInvalid sort field "X"). Routes without declared sortings skip this check. - Error Collection: All errors are collected into
ValidationErrorObject[].
Automatic Response
If one or more validation errors are found, the middleware short-circuits the request lifecycle. It does not call the next middleware or the controller. Instead, it immediately returns aBadValidationApivalkResponse (HTTP 422 Unprocessable Entity).
Example Error Response
Benefits
- Clean Controllers: Your controllers never need to contain validation logic. By the time they are executed, you are guaranteed that the input is valid and correctly typed.
- Consistency: Validation errors follow a standardized format across your entire API.
- Synchronized Docs: Since validation is driven by the documentation, your API’s behavior always matches what is described in your generated OpenAPI specification.
Usage
Enable the middleware in your configuration:Translate Validation Messages
Validation messages are English. To translate them, pass aValidationMessageTranslatorInterface to the middleware. It receives the ValidatorResult and the request locale, and returns the text to send. The error key and the parameter stay unchanged.
The error key is usually one of the ValidatorResult constants. For an unknown sort field it is free text (Invalid sort field "X"), so return getLocalizedErrorMessage() for every key you do not translate.