Larastan: Errors after update from v0.7.1 on Eloquent BelongsToMany relations

Created on 24 Apr 2021  路  4Comments  路  Source: nunomaduro/larastan

  • Larastan Version: >= 0.7.2
  • --level used: 5

Description

When updating from 0.7.1 to 0.7.2 or higher, I suddenly get analyzer errors on chained where() calls on Eloquent BelongsToMany.

Example errors:

  215    Call to an undefined method Illuminate\Database\Eloquent\Relations\BelongsToMany::where().      
  242    Call to an undefined method Illuminate\Database\Eloquent\Relations\BelongsToMany::whereNull().  
  424    Call to an undefined method Illuminate\Database\Eloquent\Relations\BelongsToMany::where().      
  521    Call to an undefined method Illuminate\Database\Eloquent\Relations\BelongsToMany::count().      
  539    Call to an undefined method Illuminate\Database\Eloquent\Relations\BelongsToMany::whereIn().    
  571    Call to an undefined method Illuminate\Database\Eloquent\Relations\BelongsToMany::where().      
  672    Call to an undefined method Illuminate\Database\Eloquent\Relations\BelongsToMany::where().      
  683    Call to an undefined method Illuminate\Database\Eloquent\Relations\HasMany::where(). 

Laravel code where the issue was found

// Line 424 from above
$item->owners()->where('user_id', $user->id)->exists();

These all reported as correct on 0.7.1 and the actual code does actually work as intended.
No other changes where made. I can toggle between a successfull analyzer run and a failing one only by switchting the Larastan version.

This is what the owners() definition looks like:

    public function members(): BelongsToMany
    {
        return $this
            ->belongsToMany(User::class, 'item_role', 'item_id', 'user_id')
            ->using(ItemRole::class)
            ->withPivot('role')
            ->withTimestamps();
    }

    public function owners(): BelongsToMany
    {
        return $this->members()->where('role', '=', 'owner');
    }

It does not complain about uses of members()->where() only of owners()->where(). So it seems Larastan no longer understands that chaining...

All 4 comments

Hello! Thank you for your report.
Are generics present in your owners() definition? Could you share the complete function?

I updated the question with the implementation of owners(). Thanks for looking into this!

BelongsToMany uses generics:
https://github.com/nunomaduro/larastan/blob/66b4ca1ed512de0bb4195573a04968ef3a941b7b/stubs/BelongsToMany.stub#L6

    /**
     * @return BelongsToMany<Users>
     */
    public function owners(): BelongsToMany

Please do not do as I write, use FQCN in PHPDoc blocks.
Consider repeating this for members().

Has it resolved Call to an undefined method errors?

Yes! Adding the generic types to the doc comments solves it.
Thank you very much for the hint! 馃檹

Was this page helpful?
0 / 5 - 0 ratings