Увійти Реєстрація
Блог Серії
Кар'єра
Вакансії Компанії
Навчання
Документація Співбесіди Тестування Відео
Екосистема
Пакети Ресурси Проєкти Інструменти Події
Інше
Про нас Реклама

Laravel Fluent Validation

sandermuller/laravel-fluent-validation
1.33.0 13 217 40k 16 липня 2026
На GitHub

Плинні конструктори правил валідації для Laravel, що забезпечують зручний інтерфейс для створення та конфігурування правил перевірки даних.

41

Поділитись

README

Laravel Fluent Validation

Fluent validation rule builders for Laravel

Latest Version on Packagist GitHub Tests Action Status GitHub PHPStan Action Status Total Downloads License Laravel Compatibility

Write Laravel validation rules with IDE autocompletion instead of memorizing string syntax. Each rule type exposes only the methods that apply to it: FluentRule::string() won't offer digits(), FluentRule::date() won't offer mimes(). each() and children() keep parent and child rules in one place instead of scattered across dot-notation keys. For large arrays, the HasFluentRules trait makes wildcard validation up to 160x faster.

// Before
'name'         => 'required|string|min:2|max:255',
'email'        => ['required', 'email', Rule::unique('users')->ignore($id)],
'role'         => Rule::when($isAdmin, 'required|string|in:admin,editor'),
'items'        => 'array',
'items.*.id'   => 'required|integer|exists:items,id',
'items.*.name' => 'required|string|max:255',

// After
'name'  => FluentRule::string('Full Name')->required()->min(2)->max(255),
'email' => FluentRule::email('Email')->required()->unique('users', 'email', fn ($r) => $r->ignore($id)),
'role'  => FluentRule::string()->when($isAdmin, fn ($r) => $r->required()->in(['admin', 'editor'])),
'items' => FluentRule::array()->each([
    'id'   => FluentRule::integer()->required()->exists('items', 'id'),
    'name' => FluentRule::string()->required()->max(255),
]),

Migrating an existing codebase? Jump straight to Migrating to fluent validation; a companion package automates the bulk of the rewrite.

Installation

You can install the package via composer:

composer require sandermuller/laravel-fluent-validation

Requires PHP 8.2+ and Laravel 12+. See Installation for AI-assisted development with Laravel Boost, and UPGRADING.md when upgrading from an older release.

Usage

Add the HasFluentRules trait to your form request:

use Illuminate\Foundation\Http\FormRequest;
use SanderMuller\FluentValidation\FluentRule;
use SanderMuller\FluentValidation\HasFluentRules;

class StorePostRequest extends FormRequest
{
    use HasFluentRules;

    public function rules(): array
    {
        return [
            'title'    => FluentRule::string('Title')->required()->min(2)->max(255),
            'email'    => FluentRule::email('Email')->required()->unique('users'),
            'date'     => FluentRule::date('Publish Date')->required()->afterToday(),
            'avatar'   => FluentRule::image()->nullable()->max('2mb'),
            'tags'     => FluentRule::array(label: 'Tags')->required()->each(
                              FluentRule::string()->max(50)
                          ),
            'password' => FluentRule::password()->required()->mixedCase()->numbers(),
        ];
    }
}

The label 'Title' replaces :attribute in error messages. You get "The Title field is required" instead of "The title field is required", without a separate attributes() array.

See Basic usage for the schema() builder, typing your rules() return, and using fluent rules outside form requests.

Documentation

Read the full documentation at sandermuller.github.io/laravel-fluent-validation.

Getting started

Digging deeper

  • Extending parent rules: child form requests, modifyEach, modifyChildren, returning a RuleSet
  • Livewire: HasFluentValidation trait, Filament workaround
  • Performance: O(n) wildcards, pre-evaluation, fast-check closures, batched DB
  • Benchmarks: the measured numbers and the rule sets behind them
  • RuleSet: build, compose, inspect, escape hatches, method reference
  • Validating with a RuleSet: validate(), check(), unknown fields, error bags
  • Testing: FluentRulesTester, Pest expectations
  • Rule reference: all types, modifiers, conditionals, macros

Migration and tooling

Contributing

Please see CONTRIBUTING for details.

Changelog

Please see CHANGELOG for more information on what has changed recently.

Security vulnerabilities

Please review our security policy on how to report security vulnerabilities.

Credits

License

MIT License. Please see License File for more information.

Читати в документації

Коментарі

Увійдіть, щоб залишити коментар

Будьте першим, хто залишить коментар!

Схожі пакети

Laravel Debugbar

barryvdh/laravel-debugbar

Інтеграція PHP Debugbar у Laravel для відлагодження та аналізу роботи додатку.

19,277 v4.4.3 13 11

Pest

pestphp/pest

Тестовий фреймворк з лаконічним синтаксисом поверх PHPUnit: тести описуються функціями замість класів. Має паралельний запуск, тести архітектури, покриття і мутаційне тестування.

11,667 v5.1.1 2

Rector

rector/rector

Автоматичний рефакторинг і оновлення коду: піднімає синтаксис до нової версії PHP, застосовує набори правил для Laravel і виправляє застарілі API масово, а не вручну по файлах.

10,405 2.6.3 1

Larastan

nunomaduro/larastan

Larastan — це розширення phpstan/phpstan для Laravel, яке дозволяє виявляти помилки у коді без його запуску.

6,500 v3.11.0 13 9

Larastan

larastan/larastan

Статичний аналіз для Laravel: вчить PHPStan розуміти фасади, магічні методи Eloquent і контейнер. Ловить помилки типів і неіснуючі методи до того, як код дійде до тестів.

6,482 v3.10.0 13 1

Laravel Backup

spatie/laravel-backup

Пакет для створення резервних копій вашого Laravel-додатку.

6,018 10.3.2 13 10