jrdavidson's avatar

L9 Attribute Not Recognized by Larastan

I'm trying to figure out why Larastan is not seeing a property on my model when I have it set inside of my ide_helper_models.php file.

Provided error from larastan: Access to an undefined property App\Models\User::$currentTeam

App/Models/Traits/MemberOfATeam.php

/**
 * @return \Illuminate\Database\Eloquent\Casts\Attribute
*/
public function currentTeam(): Attribute
{
    return Attribute::make(
        get: fn () => $this->teams()->wherePivotNull('left_at')->first(),
    );
}
namespace App\Models{
    /**
     * App\Models\User.
     *
     * @property int $id
     * @property string $name
     * @property \Illuminate\Support\Carbon|null $created_at
     * @property \Illuminate\Support\Carbon|null $updated_at
     * @property \Illuminate\Support\Carbon|null $deleted_at
     * @property-read \App\Models\Team|null $currentTeam
     ...
     * @method static \Illuminate\Database\Query\Builder|User withTrashed()
     * @method static \Illuminate\Database\Query\Builder|User withoutTrashed()
     */
    class User extends \Eloquent
    {
    }
}
0 likes
2 replies
jrdavidson's avatar

I've done further research on this issue and can't find an answer. Has anyone experienced this situation before?

Kobayakawa's avatar
Level 8

Hi,

First of all Larastan does not read the ide_helper_models.php file. That's why you couldn't solve your issue.

Second of all to make Larastan recognize Laravel 9 style attributes you need to:

  1. Make the method protected
  2. Add generic return type in the PHPDocs of the method.

So for your example, this should fix it:

/**
 * @return \Illuminate\Database\Eloquent\Casts\Attribute<Team, never>
*/
proteted function currentTeam(): Attribute
{
    return Attribute::make(
        get: fn () => $this->teams()->wherePivotNull('left_at')->first(),
    );
}

Inside the generic types the first type is for the get second is for set. Looking at your example looks like you'll use only getter. And currentTeam would return the Team model, so I wrote Attribute<Team, never>

10 likes

Please or to participate in this conversation.