LaraflareDocsFrameworkPackagesReleases13.x

Docs / Packages / Precognition

Precognition

Introduction

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.

When laraflare receives a "precognitive request", it will execute all of the route's middleware and resolve the route's controller dependencies, including validating form requests - but it will not actually execute the route's controller method.

Note

A precognitive request is an ordinary request carrying a Precognition: true header. A Precognition-Validate-Only header lists the fields to validate, and a request that passes validation is answered with a 204 and a Precognition-Success: true header. Any frontend library that speaks this protocol works with laraflare; laraflare does not ship a client of its own.

Live Validation

Using Vue

Using Precognition, you can offer live validation experiences to your users without having to duplicate your validation rules in your frontend Vue application (the screens are Vue, in resources/js). 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 precognitive middleware (the HandlePrecognitiveRequests class) should be added to the route definition. You should also create a form request to house the route's validation rules:

Route.post('/users', [UserController, 'store']).middleware('precognitive');
import { FormRequest } from '@laraflare/framework';

export class StoreUserRequest extends FormRequest {
  override rules() {
    return {
      name: ['required', 'string'],
      email: ['required', 'email'],
    } as const;
  }
}

Next, install a Precognition frontend client for Vue. It creates a form object from the HTTP method (post), the target URL (/users), and the initial form data. To enable live validation, invoke the form's validate method on each input's change event, providing the input's name.

As the form is filled by the user, the client sends a debounced "precognitive" validation request to your application, and the validation rules in the route's form request provide the live validation output. Any validation errors returned during a validation request or a form submission populate the form's errors object, and a form input only appears as valid or invalid once it has changed and a validation response has been received.

If you are validating inputs the user has not yet interacted with, such as in a "wizard" where every visible input is validated before moving to the next step, pass the field names you wish to validate to the client's validate method, and laraflare sends them in the Precognition-Validate-Only header. Only the rules for those fields are run.

Validating Arrays

You may use wildcards to validate fields within arrays or nested objects. Each * matches a single path segment:

// Validate email for all users in an array...
form.validate('users.*.email');

// Validate all fields in a profile object...
form.validate('profile.*');

// Validate all fields for all users...
form.validate('users.*.*');

Customizing Validation Rules

It is possible to customize the validation rules executed during a precognitive request by using the request's isPrecognitive method.

For example, on a user creation form, we may want to validate that a password is "uncompromised" only on the final form submission. For precognitive validation requests, we will simply validate that the password is required and has a minimum of 8 characters. Using the isPrecognitive method, we can customize the rules defined by our form request:

import { FormRequest, Password } from '@laraflare/framework';

export class StoreUserRequest extends FormRequest {
  /**
   * Get the validation rules that apply to the request.
   */
  override rules() {
    return {
      password: [
        'required',
        this.isPrecognitive()
          ? Password.min(8)
          : Password.min(8).uncompromised(),
      ],
      // ...
    } as const;
  }
}

Handling File Uploads

By default, Precognition does not upload or validate files during a precognitive validation request. This ensures that large files are not unnecessarily uploaded multiple times.

Because of this behavior, you should ensure that your application customizes the corresponding form request's validation rules to specify the field is only required for full form submissions:

/**
 * Get the validation rules that apply to the request.
 */
override rules() {
  return {
    avatar: [
      ...(this.isPrecognitive() ? [] : ['required']),
      'image',
      'mimes:jpg,png',
      'dimensions:ratio=3/2',
    ],
    // ...
  } as const;
}

If you would like to include files in every validation request, you may invoke the validateFiles function on your client-side form instance, if your client provides one.

Managing Side-Effects

When adding the precognitive middleware to a route, you should consider if there are any side-effects in other middleware that should be skipped during a precognitive request.

For example, you may have a middleware that increments the total number of "interactions" each user has with your application, but you may not want precognitive requests to be counted as an interaction. To accomplish this, we may check the request's isPrecognitive method before incrementing the interaction count:

import { type Request } from '@laraflare/framework';

export class InteractionMiddleware {
  /**
   * Handle an incoming request.
   */
  async handle(request: Request, next: (request: Request) => Promise<Response>): Promise<Response> {
    if (!request.isPrecognitive()) {
      await Interaction.incrementFor(request.user());
    }

    return next(request);
  }
}

Testing

If you would like to make precognitive requests in your tests, the TestCase includes a withPrecognition helper which will add the Precognition request header.

Additionally, if you would like to assert that a precognitive request was successful, e.g., did not return any validation errors, you may use the assertSuccessfulPrecognition method on the response:

import { test } from '../Pest';

test('it validates registration form with precognition', async function () {
  const response = await this.withPrecognition().post('/register', {
    name: 'Taylor Otwell',
  });

  response.assertSuccessfulPrecognition();

  expect(await User.count()).toBe(0);
});
Adapted from Laravel's documentation, Copyright (c) Taylor Otwell, used under the MIT License.