Precognition

Live Validation with Precognition

Precognition 176 checks fields as the user fills them in, against the server's own rules. With ->middleware(HandlePrecognitiveRequests::class) on products.store, a request carrying Precognition: true runs the middleware and the form request but never the controller, and Precognition-Validate-Only limits it to the fields the user has touched:

Output of 73
$ P='Precognition: true'; V='Precognition-Validate-Only'; G='^(HTTP|Precog|Vary|\{)'
$ curl -si $A -H "$H" -H "$J" -H "$P" -H "$V: sku" -d 'sku=bk-1001&name=' $B/products \
    | grep -E "$G" | fold -w 90
HTTP/1.1 422 Unprocessable Content
Precognition: true
Vary: Precognition
{"message":"Another book already uses SKU BK-1001.","errors":{"sku":["Another book already
 uses SKU BK-1001."]}}
$ curl -si $A -H "$H" -H "$J" -H "$P" -H "$V: sku,name" -d 'sku=bk-1009&name=Dune' \
    $B/products | grep -E "$G"
HTTP/1.1 204 No Content
Precognition-Success: true
Precognition: true
Vary: Precognition

The empty name went unreported, and the 204 created nothing (the product count stayed at 2). In the browser, laravel-precognition-vue, -react and -alpine (2.0.0 on npm 2,036 ) provide a form object with validate('sku'), invalid('sku') and errors; Inertia 515,106 has it built in since 2.3 as useForm({...}).withPrecognition('post', '/products').