I want to check if people are friends. I want to check if in a row both the authenticated user exists and the profile of visiting user.
My code
public static function areFriends($id) {
$user = Auth::user()->id;
$friend = User::with(array('friends' => function($query) use ($id, $user) {
$query->where('friend_id', '=', $id);
$query->where('user_id', '=', $id);
$query->where('friend_id', '=', $user);
$query->where('user_id', '=', $user);
}))->first();
if ( ! $friend ) {
return false;
}
return true;
}
// View
@if ( User::areFriends($user->id) )
Add friend
@else
Friends
@endif
Friends is a pivot table code is
public function friends() {
return $this->belongsToMany('Trinity\Users\User', 'friends', 'user_id', 'friend_id');
}
Have you ever tried this?
$friend = User::whereHas('friends', function($query) use ($id, $user)
{
$query->where('friend_id', '=', $id)->where('user_id', '=', $user);
})->count();
But there is an option that, user_id is the visiting user id or the other way around.
I see your point.
Make this change:
$query->where('friend_id', '=', $id)->where('user_id', '=', $user)->orWhere('friend_id', '=', $user)->where('user_id', '=', $id);
I got it working with this
$friend = $this->friends()->where('friend_id', '=', $id)->where('user_id', '=', $user)->orWhere('friend_id', '=', $user)->where('user_id', '=', $id)->first();
Sign in to participate in this thread!
The Laravel portal for problem solving, knowledge sharing and community building.
The community