Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

mrtsglk's avatar

Laravel 5.5 WhereIn query with null

return $places = Place::where('name', 'like', '%' . $request->name . '%') ->whereHas('eatCategories', function($q) use($kitchen){ $q->WhereIn('eat_category_id', $kitchen); }) ->whereHas('services', function($q) use($service){ $q->WhereIn('service_id', $service); }) ->whereHas('paymentMethods', function($q) use($payment){ $q->WhereIn('place_attribute_id', $payment); })->get(); My query is working but if the variables are empty, the query is not working until all is full.

$q->WhereIn('eat_category_id', $kitchen); If $kitchen is empty, how can I resume the query?

My route :

Route::get('/filter-places/{name?}/{kitchen?}/{service?}/{payment?}', 'SystemController@filterPlaces');

0 likes
1 reply
lostdreamer_nl's avatar

Please, next time put your code in between 6 backticks (3 backticks on 1 line, then your code underneath, followed by again 3 backticks on one line) to get the proper formatting.

To answer: If you need those parameters in the query you could set the parameters in the URI to be required.

If you do not need the parts of the query that dont have parameters set yet, you could split the query to attach the optional parts like this:

$query = $places = Place::where('name', 'like', '%' . $request->name . '%');
if(!empty($kitchen)) {
    $query = $query->whereHas('eatCategories', function($q) use($kitchen){ 
        $q->whereIn('eat_category_id', $kitchen); 
    });
}
if(!empty($service)) {
    $query = $query->whereHas('services', function($q) use($service){ 
        $q->whereIn('service_id', $service); 
    });
}
if(!empty($payment)) {
    $query = $query->whereHas('paymentMethods', function($q) use($payment){ 
        $q->whereIn('place_attribute_id', $payment); 
    });
}
return $query->get();

Please or to participate in this conversation.