Home > Back-end >  How to get absolute value by where condition in laravel?
How to get absolute value by where condition in laravel?

Time:06-03

               public function getList(Request $request)
              {
                 $keyword = $request->keyword;
                 $status = $request->status;
                 $userId = $request->userId;
                 $list = DB::table('user')
                    ->selectRaw("user.id, user.name, user.email, user.status")
                    ->whereIn('user.id', $userId)
                    ->when(!empty($keyword), function ($query) use ($keyword) {
                        $query->where('user.name', 'like', '%' . $keyword . '%');
                        $query->orWhere('user.email', 'like', '%' . $keyword . '%');
                    })
                    ->when(!empty($status), function ($query) use ($status) {
                        $query->where('user.status', '=', $status);
                    });
                    $list->get()->toArray();
              }

In laravel i am doing search function by email, name and status. The above code worked out..But there is a small problem:

              {
                    "id": 10,
                    "name": "jony",
                    "email": "[email protected]",
                    "createdAt": "05-05-2021 08:43:05",
                    "status": "2"
                },
                {
                    "id": 11,
                    "name": "test",
                    "email": "[email protected]",
                    "createdAt": "05-05-2021 08:43:05",
                    "status": "1",
                }

When I enter keyword with the keyword jony it gets 2 such items, this is correct.

BUT when I set status equal to 1 or equal to 2 the result stays the same.. Is there any way to get the result according to the correct status. Please advise me. Thanks.

CodePudding user response:

The problem is on your orWhere clause, you may want to enclose that to a group (put the query into a parentheses, for more info go HERE).

Here's what you want to to achieve:

public function getList(Request $request)
{
    $keyword = $request->keyword;
    $status = $request->status;
    $userId = $request->userId;
    $list = DB::table('user')
    ->selectRaw("user.id, user.name, user.email, user.status")
    ->whereIn('user.id', $userId)
    ->when(!empty($keyword), function ($query) use ($keyword) {
        $query->where(function ($query) use ($keyword) {
            $query->where('user.name', 'like', '%' . $keyword . '%');
            $query->orWhere('user.email', 'like', '%' . $keyword . '%');
        });
    })
    ->when(!empty($status), function ($query) use ($status) {
        $query->where('user.status', '=', $status);
    });
    $list->get()->toArray();
}
  • Related