Larastan: Problems with eloquent relationships

Created on 19 Oct 2020  路  4Comments  路  Source: nunomaduro/larastan

  • Larastan Version: 0.6.4
  • --level used: default

Description

Within the User model I have the following relationship

public function coupons()
{
        return $this->belongsToMany(Coupon::class);
}

Which returns the following error when analysed
Access to an undefined property App\Models\User::$coupons.

Laravel code where the issue was found

Such error is caused by the following line within the _UserController_:

$user->coupons->count();

Most helpful comment

Hi,

You need to define the return type of the relation method. Either in the docblocks

/**
 * @return BelongsToMany
 */
public function coupons()
{
    return $this->belongsToMany(Coupon::class);
}

or as the native return type

public function coupons(): BelongsToMany
{
    return $this->belongsToMany(Coupon::class);
}

then Larastan will understand the relation and property access.

All 4 comments

Hi,

You need to define the return type of the relation method. Either in the docblocks

/**
 * @return BelongsToMany
 */
public function coupons()
{
    return $this->belongsToMany(Coupon::class);
}

or as the native return type

public function coupons(): BelongsToMany
{
    return $this->belongsToMany(Coupon::class);
}

then Larastan will understand the relation and property access.

None of the methods described work

@grcasanova Are you getting the same error? Can you share the updated code snippet to reproduce it?

Ok solved. Two notes for reference.

  • types have capital letter: HasOne, BelongsTo, HasMany, etc
  • if using return types, remember to reference them at the beginning with:
    use Illuminate\Database\Eloquent\Relations\HasOne;
Was this page helpful?
0 / 5 - 0 ratings

Related issues

Gummibeer picture Gummibeer  路  3Comments

gitetsu picture gitetsu  路  4Comments

jdrieghe picture jdrieghe  路  4Comments

JeroenVanOort picture JeroenVanOort  路  3Comments

bogdankharchenko picture bogdankharchenko  路  4Comments