Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel - Friendship

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:

  • id
  • user_id
  • friend_id
  • status

Here is the point, I go to an user page, and Ii wanna see how is my relation with this user, 4 solutions:

  • We are friends
  • We're not
  • He doesn't have accepted the request yet
  • I have to confirm or not.

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:

  • The users are friend, so either ('user_id', Auth::user()->id)->and ('friend_id', $friend->id) or the inverse ('user_id', $friend->id)->and ('friend_id', Auth::user()->id), it has to check in the 2 senses
  • I sent request and have to wait for his answer
  • I received the request and have to accept it.
  • We're not friend and so, i can add him.

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.

like image 334
Azilhan Avatar asked Oct 20 '22 13:10

Azilhan


1 Answers

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();
}
like image 173
Eduardo Stuart Avatar answered Oct 24 '22 12:10

Eduardo Stuart