Skip to content
Advertisement

Laravel 8 – Get search result in friend lists

I am Working on laravel 8 version. I have two Models

User, FriendList

were table structure is as following.

User

id      | name      | email         | . . . .  | is_individual
--------------------------------------------------------
180     | John      | John@gg.com   | . . . .  | 1
181     | Bobby     | Bobby@gg.com  | . . . .  | 0
192     | Hellen    | Hellen@gg.com | . . . .  | 0
253     | Jason     | Jason@gg.com  | . . . .  | 1

FriendList

id | user_id | to_id
----------------------
1  | 180     | 181
2  | 180     | 192
3  | 180     | 253
4  | 253     | 180

i want to search result from User but condition is like it should be in friendlist and user should be individual (is_individual = 1)

I have tried following but i wan improve this.

Controller

    $user_id        = Auth::user()->id;
    $friendIds      = FriendList::getIndividulsFriendsIds( $user_id );
    $search_result  = User::whereIn('id', $friendIds)
                            ->where(function ($query) use ($request) {
                                $query->where('name', 'like', "%{$request->search}%")
                                    ->orWhere('email', 'like', "%{$request->search}%");
                                })
                            ->get();   

FriendList

static function getIndividulsFriendsIds( $id )
    {
        $user_id    = self::where('to_id', $id)->pluck('user_id')->toArray();
        $to_id      = self::where('user_id', $id)->pluck('to_id')->toArray();
        $userIds = array_unique( array_merge($user_id, $to_id) );
        return User::where('is_individual', 1)->whereIn('id',$userIds)->pluck('id')->toArray();
    }

Help me to improve this. Thanks

Advertisement

Answer

I Have found an alternate way using query as following

class MemberController extends Controller {
    const TYPE_INDIVIDUAL = 1;
    .
    .
    . 
    
    public individualSearch( SearchUserRequest $request ){
        $user_id = Auth::user()->id;
        $sql = "select * from users 
        WHERE ( name like '%".$request->search."%' OR email like '%".$request->search."%' )
        AND (users.id IN ( SELECT DISTINCT to_id FROM friend_lists 
                                WHERE friend_lists.user_id like ".$user_id.")
                   OR users.id IN ( SELECT DISTINCT user_id FROM friend_lists 
                                  WHERE friend_lists.to_id like ".$user_id.")
              )
        AND users.is_individual = ".self::TYPE_INDIVIDUAL;

        $search_result = DB::select($sql);
    }
}

Please do let me know if we still can improve this. Thanks

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement