# Precognition
* Introduction
* Live Validation
* Using Vue
* Using Vue and Inertia
* Using React
* Using React and Inertia
* Using Alpine and Blade
* Configuring Axios
* Customizing Validation Rules
* Handling File Uploads
* Managing Side-Effects
* Testing
## Introduction
Laravel Precognition allows you to anticipate the outcome of a future HTTP
request. One of the primary use cases of Precognition is the ability to
provide "live" validation for your frontend JavaScript application without
having to duplicate your application's backend validation rules. Precognition
pairs especially well with Laravel's Inertia-based [starter
kits](/docs/12.x/starter-kits).
When Laravel receives a "precognitive request", it will execute all of the
route's middleware and resolve the route's controller dependencies, including
validating [form requests](/docs/12.x/validation#form-request-validation) \-
but it will not actually execute the route's controller method.
## Live Validation
### Using Vue
Using Laravel Precognition, you can offer live validation experiences to your
users without having to duplicate your validation rules in your frontend Vue
application. To illustrate how it works, let's build a form for creating new
users within our application.
First, to enable Precognition for a route, the `HandlePrecognitiveRequests`
middleware should be added to the route definition. You should also create a
[form request](/docs/12.x/validation#form-request-validation) to house the
route's validation rules:
1use App\Http\Requests\StoreUserRequest;
2use Illuminate\Foundation\Http\Middleware\HandlePrecognitiveRequests;
3
4Route::post('/users', function (StoreUserRequest $request) {
5 // ...
6})->middleware([HandlePrecognitiveRequests::class]);
use App\Http\Requests\StoreUserRequest;
use Illuminate\Foundation\Http\Middleware\HandlePrecognitiveRequests;
Route::post('/users', function (StoreUserRequest $request) {
// ...
})->middleware([HandlePrecognitiveRequests::class]);
Next, you should install the Laravel Precognition frontend helpers for Vue via
NPM:
1npm install laravel-precognition-vue
npm install laravel-precognition-vue
With the Laravel Precognition package installed, you can now create a form
object using Precognition's `useForm` function, providing the HTTP method
(`post`), the target URL (`/users`), and the initial form data.
Then, to enable live validation, invoke the form's `validate` method on each
input's `change` event, providing the input's name:
1
11
12
13
39
Now, as the form is filled by the user, Precognition will provide live
validation output powered by the validation rules in the route's form request.
When the form's inputs are changed, a debounced "precognitive" validation
request will be sent to your Laravel application. You may configure the
debounce timeout by calling the form's `setValidationTimeout` function:
1form.setValidationTimeout(3000);
form.setValidationTimeout(3000);
When a validation request is in-flight, the form's `validating` property will
be `true`:
1
2 Validating...
3
Validating...
Any validation errors returned during a validation request or a form
submission will automatically populate the form's `errors` object:
1
2 {{ form.errors.email }}
3
{{ form.errors.email }}
You can determine if the form has any errors using the form's `hasErrors`
property:
1
2
3
You may also determine if an input has passed or failed validation by passing
the input's name to the form's `valid` and `invalid` functions, respectively:
1
2 ✅
3
4
5
6 ❌
7
✅
❌
A form input will only appear as valid or invalid once it has changed and a
validation response has been received.
If you are validating a subset of a form's inputs with Precognition, it can be
useful to manually clear errors. You may use the form's `forgetError` function
to achieve this:
1 {
5 form.avatar = e.target.files[0]
6
7 form.forgetError('avatar')
8 }"
9>
{
form.avatar = e.target.files[0]
form.forgetError('avatar')
}"
>
As we have seen, you can hook into an input's `change` event and validate
individual inputs as the user interacts with them; however, you may need to
validate inputs that the user has not yet interacted with. This is common when
building a "wizard", where you want to validate all visible inputs, whether
the user has interacted with them or not, before moving to the next step.
To do this with Precognition, you should call the `validate` method passing
the field names you wish to validate to the `only` configuration key. You may
handle the validation result with `onSuccess` or `onValidationError`
callbacks:
1
Of course, you may also execute code in reaction to the response to the form
submission. The form's `submit` function returns an Axios request promise.
This provides a convenient way to access the response payload, reset the form
inputs on successful submission, or handle a failed request:
1const submit = () => form.submit()
2 .then(response => {
3 form.reset();
4
5 alert('User created.');
6 })
7 .catch(error => {
8 alert('An error occurred.');
9 });
const submit = () => form.submit()
.then(response => {
form.reset();
alert('User created.');
})
.catch(error => {
alert('An error occurred.');
});
You may determine if a form submission request is in-flight by inspecting the
form's `processing` property:
1
### Using Vue and Inertia
If you would like a head start when developing your Laravel application with
Vue and Inertia, consider using one of our [starter kits](/docs/12.x/starter-
kits). Laravel's starter kits provide backend and frontend authentication
scaffolding for your new Laravel application.
Before using Precognition with Vue and Inertia, be sure to review our general
documentation on using Precognition with Vue. When using Vue with Inertia, you
will need to install the Inertia compatible Precognition library via NPM:
1npm install laravel-precognition-vue-inertia
npm install laravel-precognition-vue-inertia
Once installed, Precognition's `useForm` function will return an Inertia [form
helper](https://inertiajs.com/forms#form-helper) augmented with the validation
features discussed above.
The form helper's `submit` method has been streamlined, removing the need to
specify the HTTP method or URL. Instead, you may pass Inertia's [visit
options](https://inertiajs.com/manual-visits) as the first and only argument.
In addition, the `submit` method does not return a Promise as seen in the Vue
example above. Instead, you may provide any of Inertia's supported [event
callbacks](https://inertiajs.com/manual-visits#event-callbacks) in the visit
options given to the `submit` method:
1
### Using React
Using Laravel Precognition, you can offer live validation experiences to your
users without having to duplicate your validation rules in your frontend React
application. To illustrate how it works, let's build a form for creating new
users within our application.
First, to enable Precognition for a route, the `HandlePrecognitiveRequests`
middleware should be added to the route definition. You should also create a
[form request](/docs/12.x/validation#form-request-validation) to house the
route's validation rules:
1use App\Http\Requests\StoreUserRequest;
2use Illuminate\Foundation\Http\Middleware\HandlePrecognitiveRequests;
3
4Route::post('/users', function (StoreUserRequest $request) {
5 // ...
6})->middleware([HandlePrecognitiveRequests::class]);
use App\Http\Requests\StoreUserRequest;
use Illuminate\Foundation\Http\Middleware\HandlePrecognitiveRequests;
Route::post('/users', function (StoreUserRequest $request) {
// ...
})->middleware([HandlePrecognitiveRequests::class]);
Next, you should install the Laravel Precognition frontend helpers for React
via NPM:
1npm install laravel-precognition-react
npm install laravel-precognition-react
With the Laravel Precognition package installed, you can now create a form
object using Precognition's `useForm` function, providing the HTTP method
(`post`), the target URL (`/users`), and the initial form data.
To enable live validation, you should listen to each input's `change` and
`blur` event. In the `change` event handler, you should set the form's data
with the `setData` function, passing the input's name and new value. Then, in
the `blur` event handler invoke the form's `validate` method, providing the
input's name:
1import { useForm } from 'laravel-precognition-react';
2
3export default function Form() {
4 const form = useForm('post', '/users', {
5 name: '',
6 email: '',
7 });
8
9 const submit = (e) => {
10 e.preventDefault();
11
12 form.submit();
13 };
14
15 return (
16
39 );
40};
import { useForm } from 'laravel-precognition-react';
export default function Form() {
const form = useForm('post', '/users', {
name: '',
email: '',
});
const submit = (e) => {
e.preventDefault();
form.submit();
};
return (
);
};
Now, as the form is filled by the user, Precognition will provide live
validation output powered by the validation rules in the route's form request.
When the form's inputs are changed, a debounced "precognitive" validation
request will be sent to your Laravel application. You may configure the
debounce timeout by calling the form's `setValidationTimeout` function:
1form.setValidationTimeout(3000);
form.setValidationTimeout(3000);
When a validation request is in-flight, the form's `validating` property will
be `true`:
1{form.validating &&
Validating...
}
{form.validating &&
Validating...
}
Any validation errors returned during a validation request or a form
submission will automatically populate the form's `errors` object:
1{form.invalid('email') &&
{form.errors.email}
}
{form.invalid('email') &&
{form.errors.email}
}
You can determine if the form has any errors using the form's `hasErrors`
property:
1{form.hasErrors && }
{form.hasErrors && }
You may also determine if an input has passed or failed validation by passing
the input's name to the form's `valid` and `invalid` functions, respectively:
1{form.valid('email') && ✅}
2
3{form.invalid('email') && ❌}
{form.valid('email') && ✅}
{form.invalid('email') && ❌}
A form input will only appear as valid or invalid once it has changed and a
validation response has been received.
If you are validating a subset of a form's inputs with Precognition, it can be
useful to manually clear errors. You may use the form's `forgetError` function
to achieve this:
1 {
5 form.setData('avatar', e.target.value);
6
7 form.forgetError('avatar');
8 }}
9>
{
form.setData('avatar', e.target.value);
form.forgetError('avatar');
}}
>
As we have seen, you can hook into an input's `blur` event and validate
individual inputs as the user interacts with them; however, you may need to
validate inputs that the user has not yet interacted with. This is common when
building a "wizard", where you want to validate all visible inputs, whether
the user has interacted with them or not, before moving to the next step.
To do this with Precognition, you should call the `validate` method passing
the field names you wish to validate to the `only` configuration key. You may
handle the validation result with `onSuccess` or `onValidationError`
callbacks:
1
Of course, you may also execute code in reaction to the response to the form
submission. The form's `submit` function returns an Axios request promise.
This provides a convenient way to access the response payload, reset the
form's inputs on a successful form submission, or handle a failed request:
1const submit = (e) => {
2 e.preventDefault();
3
4 form.submit()
5 .then(response => {
6 form.reset();
7
8 alert('User created.');
9 })
10 .catch(error => {
11 alert('An error occurred.');
12 });
13};
const submit = (e) => {
e.preventDefault();
form.submit()
.then(response => {
form.reset();
alert('User created.');
})
.catch(error => {
alert('An error occurred.');
});
};
You may determine if a form submission request is in-flight by inspecting the
form's `processing` property:
1
### Using React and Inertia
If you would like a head start when developing your Laravel application with
React and Inertia, consider using one of our [starter
kits](/docs/12.x/starter-kits). Laravel's starter kits provide backend and
frontend authentication scaffolding for your new Laravel application.
Before using Precognition with React and Inertia, be sure to review our
general documentation on using Precognition with React. When using React with
Inertia, you will need to install the Inertia compatible Precognition library
via NPM:
1npm install laravel-precognition-react-inertia
npm install laravel-precognition-react-inertia
Once installed, Precognition's `useForm` function will return an Inertia [form
helper](https://inertiajs.com/forms#form-helper) augmented with the validation
features discussed above.
The form helper's `submit` method has been streamlined, removing the need to
specify the HTTP method or URL. Instead, you may pass Inertia's [visit
options](https://inertiajs.com/manual-visits) as the first and only argument.
In addition, the `submit` method does not return a Promise as seen in the
React example above. Instead, you may provide any of Inertia's supported
[event callbacks](https://inertiajs.com/manual-visits#event-callbacks) in the
visit options given to the `submit` method:
1import { useForm } from 'laravel-precognition-react-inertia';
2
3const form = useForm('post', '/users', {
4 name: '',
5 email: '',
6});
7
8const submit = (e) => {
9 e.preventDefault();
10
11 form.submit({
12 preserveScroll: true,
13 onSuccess: () => form.reset(),
14 });
15};
import { useForm } from 'laravel-precognition-react-inertia';
const form = useForm('post', '/users', {
name: '',
email: '',
});
const submit = (e) => {
e.preventDefault();
form.submit({
preserveScroll: true,
onSuccess: () => form.reset(),
});
};
### Using Alpine and Blade
Using Laravel Precognition, you can offer live validation experiences to your
users without having to duplicate your validation rules in your frontend
Alpine application. To illustrate how it works, let's build a form for
creating new users within our application.
First, to enable Precognition for a route, the `HandlePrecognitiveRequests`
middleware should be added to the route definition. You should also create a
[form request](/docs/12.x/validation#form-request-validation) to house the
route's validation rules:
1use App\Http\Requests\CreateUserRequest;
2use Illuminate\Foundation\Http\Middleware\HandlePrecognitiveRequests;
3
4Route::post('/users', function (CreateUserRequest $request) {
5 // ...
6})->middleware([HandlePrecognitiveRequests::class]);
use App\Http\Requests\CreateUserRequest;
use Illuminate\Foundation\Http\Middleware\HandlePrecognitiveRequests;
Route::post('/users', function (CreateUserRequest $request) {
// ...
})->middleware([HandlePrecognitiveRequests::class]);
Next, you should install the Laravel Precognition frontend helpers for Alpine
via NPM:
1npm install laravel-precognition-alpine
npm install laravel-precognition-alpine
Then, register the Precognition plugin with Alpine in your
`resources/js/app.js` file:
1import Alpine from 'alpinejs';
2import Precognition from 'laravel-precognition-alpine';
3
4window.Alpine = Alpine;
5
6Alpine.plugin(Precognition);
7Alpine.start();
import Alpine from 'alpinejs';
import Precognition from 'laravel-precognition-alpine';
window.Alpine = Alpine;
Alpine.plugin(Precognition);
Alpine.start();
With the Laravel Precognition package installed and registered, you can now
create a form object using Precognition's `$form` "magic", providing the HTTP
method (`post`), the target URL (`/users`), and the initial form data.
To enable live validation, you should bind the form's data to its relevant
input and then listen to each input's `change` event. In the `change` event
handler, you should invoke the form's `validate` method, providing the input's
name:
1
Now, as the form is filled by the user, Precognition will provide live
validation output powered by the validation rules in the route's form request.
When the form's inputs are changed, a debounced "precognitive" validation
request will be sent to your Laravel application. You may configure the
debounce timeout by calling the form's `setValidationTimeout` function:
1form.setValidationTimeout(3000);
form.setValidationTimeout(3000);
When a validation request is in-flight, the form's `validating` property will
be `true`:
1
2
Validating...
3
Validating...
Any validation errors returned during a validation request or a form
submission will automatically populate the form's `errors` object:
1
2
3
You can determine if the form has any errors using the form's `hasErrors`
property:
1
2
3
You may also determine if an input has passed or failed validation by passing
the input's name to the form's `valid` and `invalid` functions, respectively:
1
2 ✅
3
4
5
6 ❌
7
✅❌
A form input will only appear as valid or invalid once it has changed and a
validation response has been received.
As we have seen, you can hook into an input's `change` event and validate
individual inputs as the user interacts with them; however, you may need to
validate inputs that the user has not yet interacted with. This is common when
building a "wizard", where you want to validate all visible inputs, whether
the user has interacted with them or not, before moving to the next step.
To do this with Precognition, you should call the `validate` method passing
the field names you wish to validate to the `only` configuration key. You may
handle the validation result with `onSuccess` or `onValidationError`
callbacks:
1
You may determine if a form submission request is in-flight by inspecting the
form's `processing` property:
1
#### Repopulating Old Form Data
In the user creation example discussed above, we are using Precognition to
perform live validation; however, we are performing a traditional server-side
form submission to submit the form. So, the form should be populated with any
"old" input and validation errors returned from the server-side form
submission:
1