Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

paskwaal's avatar

PHPStan/Larastan MorphTo warning

Last week I have updated my dependencies and since then I have got a PHPStan / Laracast error I just don't seem to get resolved.

We have a Model (MenuOverviewItem) which has a MorphTo relations to multiple other Models (MenuItem|Folder|ExternalLink). We have defined it this way;

/**
 * Get the model that the overview item belongs to.
 *
 * @return MorphTo<MenuItem|Folder|ExternalLink,$this>
 */
public function item(): MorphTo
{
    return $this->morphTo(__FUNCTION__, 'item_type', 'item_id');
}

Only when running phpstan analyse (level 5) we get the following error;

Method App\Models\LinkOverviewItem::item() should return Illuminate\Database\Eloquent\Relations\MorphTo<App\Models\ExternalLink|App\Models\Folder|App\Models\MenuItem, $this(App\Models\LinkOverviewItem)> but returns Illuminate\Database\Eloquent\Relations\MorphTo<Illuminate\Database\Eloquent\Model, $this(App\Models\LinkOverviewItem)>.

Does somebody see what I am doing wrong? Initially I though I had to implement the @template logic, but I don't seems to get that working correctly.

0 likes
3 replies
NegoZiatoR's avatar

I would really like to see how this could be solved. Facing the exact same issue. Tried several different things. But it's seems like the Illuminate\Database\Eloquent\Model- part is making it really difficult to specify the type.

1 like
Lumethys's avatar

try

@return MorphTo<MenuItem,$this> | MorphTo<Folder,$this> | MorphTo<ExternalLink,$this>
paskwaal's avatar

@Lumethys Nope, still an error. Only the 'should return' part changes after that edit into;

Method App\Models\LinkOverviewItem::item() should return Illuminate\Database\Eloquent\Relations\MorphTo<App\Models\ExternalLink|, $this(App\Models\LinkOverviewItem)>|Illuminate\Database\Eloquent\Relations\MorphTo<App\Models\Folder, $this(App\Models\LinkOverviewItem)>|Illuminate\Database\Eloquent\Relations\MorphTo<App\Models\MenuItem, $this(App\Models\LinkOverviewItem)> but returns Illuminate\Database\Eloquent\Relations\MorphTo<Illuminate\Database\Eloquent\Model, $this(App\Models\LinkOverviewItem)>.

What does work is adding 'Model' itself as return type, only that whole idea of adding explicit typing as MorphTo is gone that. So calling it this; @return MorphTo<MenuItem|Folder|ExternalLink|Model,$this>

Please or to participate in this conversation.