I'm trying to do a friendship system in laravel 5 and I'm stuck. I have a friends_user table which look like this:
Here is the point, I go to an user page, and Ii wanna see how is my relation with this user, 4 solutions:
I wanna create a method that checks if a user is friend with an other, simple. I have a 'status' column which is a boolean (0 for pending and 1 for friends) The perfect solution for me would be to be able in one method to check if:
So if you can tell me where i'm wrong here, here's my logic (just for check if users are friend) : User.php
public function isFriend($slug)
{
// Get both user
$user = Auth::user();
$receiver = User::where('slug', $slug)->first();
// get list of friends (so who have status = 1)
$result = Friends::where('status', 1);
// Get users where user id is equal to connected
$result = $result->where('user_id', $user->id)->where('friend_id', $receiver->id);
$result = $result->orWhere('user_id', $receiver->id)->where('friend_id', $user->id);
$result = $result->get();
if(count($result) == 0)
return false;
return true;
}
After I do these checks in my view.
This works pretty much, but only if i (the current user) has sent the request but if it's the inverse it returns me the user even if status is at 0. I think that my $result erase the other ones isn't it? What's the solution so?
I hope it's clear, and if you can tell me how do this in a clean way, it would be great.
That's a common mistake. Beware of your "orWhere" clause.
public function isFriend($slug)
{
// Get both user
$user = Auth::user();
$receiver = User::where('slug', $slug)->first();
// get list of friends (so who have status = 1)
$result = Friends::where('status',1)->where(function($query) use ($receiver,$user)
{
$query->where([
'user_id' => $user->id,
'friend_id' => $receiver_id
])->orWhere([
'user_id' => $receiver->id,
'friend_id' => $user->id
]);
})->get();
return ! $result->isEmpty();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With