Skip to main content

How it Works

The middleware intercepts the request before it reaches the controller and performs the following steps:
  1. 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).
  2. 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, …).
  3. Required Field Check: If a property is marked required but missing, a validation error is recorded.
  4. Filter Validation: Each filter in $request->filtering() is validated against its underlying property (required / type / custom validators).
  5. Sort Field Validation: Each Sort in $request->sorting() must correspond to a field declared on the route via Route::sorting([...]). Unknown fields sent via ?order_by=... produce a validation error (key order_by, message Invalid sort field "X"). Routes without declared sortings skip this check.
  6. 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 a BadValidationApivalkResponse (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 a ValidationMessageTranslatorInterface 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.