larastan: Model factory is not recognizing correct types when useFactory exists in BaseModel class

  • Larastan Version: v0.7.2
  • --level used: 6
  • Pull request with failing test:

Description

Model factory is not recognizing correct types in Laravel v8.50.0, works on v8.44.0

Call to an undefined method Illuminate\Database\Eloquent\Collection|Illuminate\Database\Eloquent\Model::pauses()

Laravel code where the issue was found

        $hour = EmpHour::factory()->create([]);

        $hour->pauses()->save($break, ['quantity' => 1]);

I tried dev-master for the newest changes and the error still happens.

About this issue

  • Original URL
  • State: closed
  • Created 3 years ago
  • Comments: 21 (9 by maintainers)

Most upvoted comments

For anybody who still get errors and lands here:

It took me several hours to figure out that PHPStan caches the results of analysis runs. To fix the issues with the factories, you need to add the @extends doc comment as described above. However, this change does not clear the PHPStan cache, so you will still get errors. You should run vendor/bin/phpstan clear-result-cache to make sure you don’t see cached errors that are actually solved by changed in the comments.

         Access to an undefined property                                        
         Illuminate\Database\Eloquent\Collection|Illuminate\Database\Eloquent\  
         Model::$id.                                                            

  109    Call to an undefined method                                            
         Illuminate\Database\Eloquent\Collection|Illuminate\Database\Eloquent\  
         Model::pauses().   
         

I found out the error. I am using a BaseModel that all my models extend and I only have the use HasFactory in the basemodel.

If I move the use HasFactory to the model in question it works

@erikroznbeker In your case it works correctly. It determines that the model is User. But the issue is we can’t determine if it returns single model or a collection. But you’ll get this error only on level 7 and higher.

@crissi What is the error you are getting?

For example for User model you have UserFactory. So in the database/factories/UserFactory.php you should have

/** @extends Factory<User> */
class UserFactory extends Factory
{
    ....
}

Can you confirm it is like this?