1 month ago

MorphTo with specific methods

Posted 1 month ago by marcorieser


I have a User model which morphs to Employee and Guardian (like parent).

protected function role()
        return $this->morphTo();

Now \App\Models\User::first()->role returns either a guardian or an employee, which is great.

But I'd prefer to call e.g.\App\Models\User::first()->guardian which would return me the linked Guardian model or null / empty collection (not sure about this) if it is an employee. The same with \App\Models\User::first()->employee.

On the one hand I want to do this to make sure that the right role is available instead of first checking $user->isGuardian(). On the other hand to get autocompletion in PhpStorm.

I tried to link it explicit by using

public function guardian()
        return $this->belongsTo(Guardian::class, 'role_id');

But now \App\Models\User::first()->guardian gives me the relation to the guardian (even if the user is of role Employee) instead of an empty collection.

Is there a way to make $this->morphTo() link to a specific model and otherwise return an empty collection?

Please sign in or create an account to participate in this conversation.