$ lexprog.com

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

[June 18, 2025] Laravel

Laravel Custom Validation: Rule Objects

Laravel Custom Validation: Rule Objects

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

Laravel Custom Validation: Rule Objects

Tip: Generate Rule Class

php artisan make:rule ValidPhoneNumber

Gotcha: passes() Method

public function passes($attribute, $value): bool
{
    return preg_match('/^\+?\d{10,15}$/', $value);
}

Returns true if valid, false if invalid.

Tip: Custom Error Message

public function message(): string
{
    return 'The :attribute must be a valid phone number.';

Gotcha: Implicit Rules

class RequiredIfAdmin implements ImplicitRule {}

Implicit rules run even if the field is empty or missing.

Tip: Access Other Fields

public function passes($attribute, $value): bool
{
    $type = request()->input('type');
    return $type === 'premium' ? $value > 100 : true;
}

Gotcha: Rule Objects Are Reusable

'title' => [new ValidTitle(), 'max:255'],

Combine rule objects with string rules.

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

The single best investment in Laravel code quality I've made is automated static analysis. Tools like Larastan catch type errors, missing imports, and incorrect method calls before they reach production. I configure it as a pre-commit hook with increasing strictness levels. The first time Larastan catches a 'Call to method on null' error before deployment, you'll be converted. It's not about eliminating bugs — it's about catching the boring ones automatically so code review focuses on architecture.

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

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