Search code examples
laravelmodellaravel-8mutual-friendship

Laravel How to find Mutual Friends from model?


I am using laravel 8. I want to find the mutual friends of entries and profiles.

Please ask me if it is not clear...

My friends table;

user_friends;
id | user_id | user_friend_id
1  | 10      | 20
2  | 20      | 10

In My User Model;

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

    public function friendsOf(){
     return $this->belongsToMany(User::class, 'user_friends', 'user_friend_id', 'user_id');
    }

How can I find mutual friends of the profile with respect to authenticated user?

Example;

@foreach($user as $entry)
{{ count( $entry->mutual(Auth::id()) ) }}
  @foreach($entry->mutual(Auth::id()) as $item)
   {{ $item->name }}
   ...
  @endforeach
@endforeach

Solution

  • I make this work by using helpers. I create helpers.php on App folder and create a function.

    function mutualFriends($id){
     $profile = User::where('id', $id)->first();
     $profileFriends = $profile->friends;
     $profileFriendsIds = [];
       foreach ($profileFriends as $entry){
         $profileFriendsIds[] = $entry->id;
        }
     $loggedUserFriends = Auth::user()->friends->whereIn('id', $profileFriendsIds);
    
     return $loggedUserFriends;
    }
    

    and now I am calling the function from view like;

    {{count(mutualFriends(Auth::id()))}}
    

    or

    @foreach(mutualFriends($profile->id) as $entry)
    ...
    @endforeach