All rules that are specific to Laravel applications are listed here with their configurable options.
Checks for method calls on instances of Illuminate\Support\Collection
and their
subclasses. If the same result could have been determined
directly with a query then this rule will produce an error.
This rule exists to reduce unnecessarily heavy queries on the database
and to prevent unneeded loops over Collections.
User::all()->count();
$user->roles()->pluck('name')->contains('a role name');
Will result in the following errors:
Called 'count' on Laravel collection, but could have been retrieved as a query.
Called 'contains' on Laravel collection, but could have been retrieved as a query.
To fix the errors, the code in the previous example could be changed to:
User::count();
$user->roles()->where('name', 'a role name')->exists();
This rule is enabled by default. To disable it completely, add:
parameters:
noUnnecessaryCollectionCall: false
to your phpstan.neon
file.
You can also configure the collection methods which this rule
checks for. By default, all collection methods are checked.
To only enable a specific set of methods, you could set the
noUnnecessaryCollectionCallOnly
configuration key. For example:
parameters:
noUnnecessaryCollectionCallOnly: ['count', 'first']
will only throw errors on the count
and first
methods.
The inverse is also configurable, to not throw an exception
on the contains
method, one could set the following value:
parameters:
noUnnecessaryCollectionCallExcept: ['contains']
NOTE: This rule is currently in beta! If you want to improve it's analysis you can check out the issue here and contribute!
default: false
This rule is disabled by default. You can enable it by putting
parameters:
checkModelProperties: true
to your phpstan.neon
file.
This rule checks every argument of a method or a function, and if the argument has the type model-property
, it will try to check the given value against the model properties. And if the model does not have the given property, it'll produce an error.
User::create([
'name' => 'John Doe',
'emaiil' => '[email protected]'
]);
Here we have a typo in email
column. So if we run analysis on this file Larastan will generate the following error:
Property 'emaiil' does not exist in App\User model.
This check will be done automatically on Laravel's core methods where a property is expected. But you can also typehint the model-property
in your own code to take advantage of this analysis.
You can define a function like this:
/**
* @phpstan-param model-property<\App\User> $property
*/
function takesOnlyUserModelProperties(string $property)
{
// ...
}
And if you call the function above with a property that does not exist in User model, Larastan will warn you about it.
// Property 'emaiil' does not exist in App\User model.
takesOnlyUserModelProperties('emaiil');