0

I have a query for multiple searches, the problem is with one of them, I get a correct result from it, but in combination with the rest, I get the wrong response for the rest of the fields.

//I get the correct result for first if, but the second one returns a wrong response.
        if ($request->has('search_fullname') && !is_null($request->search_fullname)) {
            $query->where('full_name', 'ILIKE', $request->search_fullname . '%')
                ->orWhere('full_name', 'ILIKE', '% ' . $request->search_fullname . '%');
        }

        if ($request->has('search_gender') && !is_null($request->search_gender)) {
            $query->where('gender', '=', $request->search_gender);
        } //like this if I have many more, the problem is strict from the first one

1 Answer 1

2

First of all, when you apply where(A)->orWhere(B) to query and apply new where(C)... method, it will become:

where (A and C and D ...) or B

you need to change it to

where (A or B) and C and D ....

so the first query need to be like this:

if ($request->has('search_fullname') && !is_null($request->search_fullname)) {
    $query->where(function($q) {
          $q->where('full_name', 'ILIKE', $request->search_fullname . '%')
            ->orWhere('full_name', 'ILIKE', '% ' . $request->search_fullname . '%');
    })       
}

Secondly, you can use when as condition method, it will apply to a query only when the request field is not empty.

$query->when($request->input('search_fullname'), function($q) use ($request) {
    $q->where(function($q) {
        $q->where('full_name', 'ILIKE', $request->search_fullname.'%')
          ->orWhere('full_name', 'ILIKE', '% ' . $request->search_fullname . '%');
    });   
})->when($request->input('search_gender'), function($q) use ($request) {
    $q->where('gender', '=', $request->search_gender);
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.