Home / Laravel / Laravel Fluent Validation: An Object-Oriented Rule Builder

Laravel Fluent Validation: An Object-Oriented Rule Builder

Laravel Fluent Validation, by Sander Muller, is a package that replaces Laravel’s traditional string-based validation syntax with a fluent, object-oriented API. It provides IDE autocompletion and type safety, ensuring that you only apply rules that make sense for the data type being validated.

Fluent and Type-Safe Rules

Instead of concatenating strings like 'required|string|min:2|max:255', you can use a chain of methods. The API is context-aware, meaning that once you define a rule type (such as a string or a date), only the methods relevant to that type are available:

use SanderMullerLaravelFluentValidationFluentRule;
 
$rules = [
'name' => FluentRule::string()->required()->min(2)->max(255),
'published_at' => FluentRule::date()->after('today')->nullable(),
'age' => FluentRule::integer()->min(18)->max(99),
];

Nested Array Validation

The package simplifies validating nested data structures by using each() and children() methods. This allows you to define rules in a way that mirrors your data structure rather than using flat dot-notation keys:

'items' => FluentRule::array()->required()->min(1)->each(
FluentRule::children([
'id' => FluentRule::integer()->required()->exists('products', 'id'),
'quantity' => FluentRule::integer()->required()->min(1),
])
),

Performance Optimizations

Beyond the syntax improvements, the package includes several performance-focused features:

  • O(n) Wildcard Expansion: For large nested arrays, the package uses an optimized expansion algorithm that can be significantly faster than Laravel’s native O(n²) approach.
  • Fast-Check Closures: Common rules are compiled into PHP closures, allowing the validator to bypass the overhead of the main validation engine for passing values.
  • Batched Database Queries: exists and unique rules for wildcard arrays are automatically batched into a single whereIn query to reduce database load.

Integrated Messages and Labels

You can define human-readable labels and custom error messages directly within the rule chain. This removes the need to maintain separate attributes() or messages() arrays in your Form Requests:

'email' => FluentRule::string()
->email()
->label('Email Address')
->message('Please provide a valid business email.', 'email'),

Installation

You can install the package via Composer:

composer require sandermuller/laravel-fluent-validation

The package requires PHP 8.2+ and Laravel 11.0 or higher. It also includes dedicated traits for integrating with Livewire and Filament projects.

You can learn more about this package and view the full documentation on GitHub.

Source: https://laravel-news.com

Tagged:

Leave a Reply

Your email address will not be published. Required fields are marked *