简体   繁体   中英

Conditionally add where clause to eloquent query

I have a products database. I allow users to enter a search term and I display products related to their search term. I'm wanting to add the ability for the user to further filter these results by "gender" using AJAX. If the user selects a gender from a select box this is sent to the URL query string.

here is my code responsible for detecting if "gender" is in the query string.

$searchTerm = request('s');
$gender = request('gender');

$productsQuery = DB::table('products')
                ->where('title', 'LIKE', "%$searchTerm%");
if ($gender != "") {
    $productsQuery->where('gender', '=', "%$gender%");
}

$productsQuery->get(); 

When this method is called. I receive an empty collection.

Your idea and approach is correct, but you are mixing LIKE and = queries. % is a wildcard, but that can be only be used with LIKE .

So, if you want to use a wildcard and LIKE ,

if(!empty($gender)) {
    $productsQuery->where('gender', 'LIKE', "%$gender%");
}

Or if you want to match by exact text,

if(!empty($gender)) {
    $productsQuery->where('gender', $gender);
}

Your current code will search for the exact match of the literal string %male% , for example.

Keep in mind that by using a wildcard, male will also match female (as they both contain the word "male").

You should use LIKE also in the second where clause:

$productsQuery->where('gender', 'LIKE', "%{$gender%}");

EDITED

If you need to search for the exact gender you must not use wildcards at all.

$productsQuery->where('gender', '=', $gender);

Actually you can do this in one query. Just like that:

$productsQuery = DB::table('products')
->where('title', 'LIKE', '%'.$searchTerm.'%')
->where(function($query) use ($gender){
     if($gender != ""){
        $query->where('gender', '=', $gender);
      }
})
->get();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM