SuperManSL
SuperManSL

Reputation: 1306

Friendship between users in Laravel 4

I have created model so that users can be friends. I have table user_friends where user_id and friend_id are stored. The problem is, that it works only one-way. If user 1 adds user 2 as friend, user 2 will be friend of user 1 but not reverse (user 1 friend of user 2) how can I accomplish something like this?

User model

   public function friends()
{
    return $this->belongsToMany('User','user_friends','user_id','friend_id');
}

and User_Friend model

public function user()
{
    return $this->belongsToMany('User');
}

Finding friends

 $friends = User::find($user->id)->friends;

And part of controller where I save new friendship

$friendData = array('user_id' => $invite->id,); //$invite is result of $invite->save()
        $friend = User::find($user->id)->friends()->attach($friendData);

Upvotes: 0

Views: 495

Answers (1)

giannis christofakis
giannis christofakis

Reputation: 8321

One thing you can do is store and the reverse relationship.

$friendData = ['user_id' => $invite->id];

$user = User::find($user->id);
$user->friends()->attach($friendData);

$friend = User::find($invite->id);
$friend->friends()->attach($user);

Otherwise you may retrieve the reverse relationship

public function reverseFriends()
{
    return $this->hasManyThrough('User', 'User_Friend', 'friend_id', 'user_id');
}

and then merge the two collections.

Upvotes: 1

Related Questions