Real Time validation (SPA)

Let's say you have inputs and you wanna validate them in real time. how you can do that and without needing to duplicate your validation code on the frontend again ?

First you should install the Laravel Precognition frontend helpers for your SPA or your application via NPM:

npm install laravel-precognition-{SPA APP NAME}

let's say w're working with react or vue , then u must install it with 
following command like this

npm install laravel-precognition-react 
or
npm install laravel-precognition-vue

Then in your Laravel backend route u should add the 'HandlePrecognitiveRequests'

on route that u will make a request to it.

Don't forget to import it:

use Illuminate\Foundation\Http\Middleware\HandlePrecognitiveRequests;

  Route::post('/auth/login', [AuthController::class, 'login'])->middleware([HandlePrecognitiveRequests::class]);

laravel.com/docs/10.x/validation#creating-f..

Notice : Your validation codes shouldn't be in your controller directly !! instead you must create a request form then passing the request form that contains the validation rules through your method otherwise it won't work + don't forget to retrurn true instead of false in authorize method in your form request file otherwise u will get 403 error

  public function authorize(): bool
    {
        return true;
    }

Now in your laravel application config/cors.php u should pass 'precognition', 'precognition-success' in the exposed_headers array

    'exposed_headers' => ['precognition', 'precognition-success'],

Now In your component import useForm hook then you can here make your request and showing the error using validate method on the form ..

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 (
        <form onSubmit={submit}>
            <label for="name">Name</label>
            <input
                id="name"
                value={form.data.name}
                onChange={(e) => form.setData('name', e.target.value)}
                onBlur={() => form.validate('name')}
            />
            {form.invalid('name') && <div>{form.errors.name}</div>}

            <label for="email">Email</label>
            <input
                id="email"
                value={form.data.email}
                onChange={(e) => form.setData('email', e.target.value)}
                onBlur={() => form.validate('email')}
            />
            {form.invalid('email') && <div>{form.errors.email}</div>}

            <button disabled={form.processing}>
                Create User
            </button>
        </form>
    );
};

https://laravel.com/docs/10.x/precognition