$ lexprog.com

// notes from an old coder -- php, databases, and the occasional rant

[August 15, 2024] Laravel

Laravel Precognition: AJAX Validation

Laravel Precognition: AJAX Validation

────────────────────────────────────────────────────────

Laravel Precognition: AJAX Validation

Tip: Enable Precognition

Route::post('/posts', [PostController::class, 'store'])
    ->precognitive();

Gotcha: Frontend Integration

import { validate } from 'laravel-precognition';

form.validate('POST', '/posts');

Tip: Validate Before Submit

Precognition validates the form as the user types, before submission.

Gotcha: Same Validation Rules

Uses the same Form Request rules as regular validation. No duplicate rule definitions.

Tip: Error Display

@error('title')
    <span class="error">{{ $message }}</span>
@enderror

Gotcha: Network Overhead

Each validation check is an HTTP request. Debounce input to reduce requests.

Tip: Use route:cache Carefully

php artisan route:cache is fast, but it doesn't work with closure-based routes. Every time you cache routes, Laravel serializes them. If you have Route::redirect() or closure callbacks, the cache breaks. Stick to controller-based routes in production.

Tip: Model APP_KEY Rotation

Rotating APP_KEY invalidates all encrypted data — cookies, encrypted DB columns, and password reset tokens. If you must rotate (e.g., after a leak), plan a migration that re-encrypts existing data with the new key.

Gotcha: Local Scope Leaks

Global scopes defined in booted() apply to ALL queries on that model — including relationships. An innocent User::all() in admin panel might exclude soft-deleted users if a global scope is active.

Senior Insight

Precognition is one of those Laravel features that sounds minor but dramatically improves UX. The mistake teams make: they either don't use it at all (forcing full-page reloads for validation errors) or they over-engineer their own AJAX validation. Precognition handles the 80% case elegantly. I pair it with Alpine.js for a UX that feels like a SPA without the complexity.

Source: Laravel News (https://laravel-news.com/), Freek.dev (https://freek.dev/tags/laravel), Spatie Blog (https://spatie.be/blog)

────────────────────────────────────────────────────────
<-- back to posts