The more specific you get with PHPStan type declarations, the more useful they become. But sometimes, in order to cover all the variations of what types Laravel will allow, those type declarations can get a bit long and complicated to read.
For example, check out this long type declaration which covers all the possible ways of defining a form request's rules:
/** @return array<string, array<\Illuminate\Contracts\Validation\Rule|\Illuminate\Contracts\Validation\ValidationRule|string>|string> */
The flexibility of Laravel's rules is great, but that type declaration is a lot to absorb.
Recently, I read a great article by Freek about PHPStan's type aliases, which solves this problem.
You can define your own type aliases in your phpstan.neon
file, and then use them in your code:
# phpstan.neon
parameters:
typeAliases:
ValidationRules: 'array<string, array<\Illuminate\Contracts\Validation\Rule|\Illuminate\Contracts\Validation\ValidationRule|string>|string>'
Now, my type declaration in the form request is just /** @return ValidationRules */
.
Much nicer!
And if some new shape is introduced in the future, I can just update the type alias in one place instead of everywhere I used it.
This is a great quality of life improvement!
Here to help,
Joel
P.S. We have an excellent book that can help you to master Laravel validation.