Laravel Validation extension for PHPStan
AGPL-3.0 License
If the rules given to a laravel validator are a constant expression, then the shape of the array returned by \Illuminate\Validation\Validator::validated()
is known at compile-time, and can be statically analyzed.
$request = new \Illuminate\Http\Request();
$data = \Illuminate\Support\Facades\Validator::make($request->all(), [
'person.*.email' => 'required|email|unique:users',
'person.*.first_name' => 'required|string',
'person.*.age' => 'required|integer|string',
])->validated();
\PHPStan\dumpType($data);
// array{person: array<int|string, array{email: non-empty-string, first_name: string, age: numeric-string}>}
$data = $request->validate([
'person.*.email' => 'required|email|unique:users',
'person.*.first_name' => 'required|string',
'person.*.age' => 'required|integer|string',
]);
\PHPStan\dumpType($data);
// array{person: array<int|string, array{email: non-empty-string, first_name: string, age: numeric-string}>}
If the input data does not match the rules array, an \Illuminate\Validation\ValidationException
is thrown, thus preserving type safety.
To use this extension, require it in Composer:
composer require --dev jbboehr/phpstan-laravel-validation
If you also install phpstan/extension-installer then you're all set!
If you don't want to use phpstan/extension-installer
, include extension.neon
in your project's PHPStan config:
includes:
- vendor/jbboehr/phpstan-laravel-validation/extension.neon
numeric
produces the type union int|float|numeric-string
. If you know it will always be a string, you can refine the type by using numeric|string
and get a plain numeric-string
.This project is licensed under the AGPL v3+ License - see the LICENSE.md file for details.