Precognition
Laravel Rest API supports Laravel’s Precognition feature for live frontend validation.
Precognition allows you to anticipate the outcome of an HTTP request by running validation rules without executing the controller logic.
In other words, the request is “simulated” purely for validation.
Installation
Precognition support is disabled by default. To enable it, set rest.precognition.enabled
to true in your config/rest.php.
:
// config/rest.php
'precognition' => [
'enabled' => true,
],
This flag toggles Laravel’s HandlePrecognitiveRequests
middleware support.
Usage Example
Once enabled, any API endpoint generated via Rest::resource
will automatically have HandlePrecognitiveRequests
applied.
This means that any request with the Precognition
header to true will be considered precognitive.
For example, consider a search endpoint on the users resource. If the client sends:
POST /api/users/search
Precognition: true
Content-Type: application/json
{
"search": {
// ... search parameters ...
}
}
Laravel will execute all middleware and run the form request or validator rules as usual, then immediately return the validation result. In this mode:
- If the data fails validation, you will receive a 422 Unprocessable Entity with the validation errors.
- If it passes validation, you will receive a 204 No Content response and no database action is taken.
In short, the request is validated but the controller method is never called, allowing you to get “live” validation feedback from the API without performing the actual operation.