1
votes

Table friends: id, user_id, friend_id.

Table user_profiles: id, user_id, first_name...

How to get a list of the user's friends through Eloquent ORM?

user_id: 5 | friend_id: 6

user_id: 6 | friend_id 5

Similar questions:

Friendship system with Laravel : Many to Many relationship

Laravel & Eloquent - Query 'Friends' Relationship

I can not understand who calls the method getFriendsAttribute().

And how to do it Query builder.

Thanks!

1

1 Answers

2
votes

You can define relationship on User model:

class User extend Model
{
    ...

    // Get list of who sent me a friend request
    public function myFriends()
    {
        return $this->belongsToMany(get_class($this), 'friends', 'friend_id');
    }

    // Get the list of friends whom I invited
    public function friendsOf()
    {
        return $this->belongsToMany(get_class($this), 'friends', 'user_id', 'friend_id');
    }

    // Merge
    public function getFriendsAttribute()
    {
        return $this->myFriends->merge($this->friendOf);
    }
}

Then you can get the list of user's friends by $user->myFriends, to query friend by their first name: $user->myFriends()->where('first_name', '=', 'John')->get().