Laravel HasMany with included current Model on same Table

I want to have a method (with the possiblity to eager load) to return all users which are connected via user_collection_uuid including the current user. If the user_collection_id is not set it should at least return the current user.

The method I’m using (null values are automatically filtered due to hasMany):

class User extends Model {
    public function userInCollection(): HasMany
        return $this
           ->hasMany(User::class, 'user_collection_uuid', 'user_collection_uuid')
           ->orWhere('id', $this->id);


It works if the method is called directly but not eager/lazy loaded:

$user->userInCollection()->get()->count() // Collection count returns 1

The following Code should do the same except it is resolved via LazyLoading or EagerLoading. However this returns 0.

$user->userInCollection->count() // Collection count returns 0

It seems like the User which calls the HasMany method is filtered from the result.
Is there another method to do this or am I missing something? Is this the desired behaviour?

Laravel 8.26.1


Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

You can’t use your $this context in a relationship.

the easiest way to do this would be to use a custom attribute :

    public function userInCollection(): HasMany
        return $this
           ->hasMany(User::class, 'user_collection_uuid', 'user_collection_uuid');

    public function getUsersInCollectionAttribute()
        return $this->userInCollection->push($this);

you can then do this :

$user = User::with('userInCollection')->find($id);

All methods was sourced from or, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Notify of

Inline Feedbacks
View all comments
Would love your thoughts, please comment.x