1

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!

Community
  • 1
  • 1
Anton
  • 81
  • 8

1 Answers1

2

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().

Rifki
  • 3,440
  • 1
  • 18
  • 24
  • I have a relationship. But I can get a list of only user_id or user_friend. How to combine requests ? – Anton May 30 '16 at 08:24
  • I didn't get your question about "But I can get a list of only user_id or user_friend. How to combine requests ?" can you please more clear what do you want to achieve? – Rifki May 30 '16 at 08:28
  • Did you meant get friend list by certain `user_id`? – Rifki May 30 '16 at 08:32
  • If I write so: return $this->belongsToMany(get_class($this), 'users_friends', 'friend_id'); I got those who sent me a friend request/ invitation If I write so: return $this->belongsToMany(get_class($this), 'users_friends', 'user_id', 'friend_id'); I got the list of friends whom I invited. But I am not visible a their friend's list. – Anton May 30 '16 at 08:40
  • @Anton if you want display both friends who invites you and your invited friends then you can merge those relationship using `merge()`, see edited answer. – Rifki May 30 '16 at 08:59
  • Strangely , I have tried to do so , but it did not work . And now it works! Many thanks! – Anton May 30 '16 at 09:10