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

pedroroccon's avatar

Building queries with multiple search filters

Hello! First thanks to watch my topic.

I think that my question is simple. I want to build my query while the user fills some specific fields. If the user don't fill or change the field, this option won't will be in my final query. It's like a start query that will be incremented with "wheres" according to the user's filter choice. Something like:

$product = Product::where('active', '=', 'yes');
$input = Input::all();

if(isset($input['type'])):
    $product->where('type', '=', $input['type']);
endif;

if(isset($input['date_created'])):
    $product->where('created_at', '>', $input['date_created']);
endif;

if(isset($input['code'])):
    $product->where('code', '=', $input['code']);
endif;

$product->orderBy('id', 'desc')->get();

return view('product.index', compact('product'));

In this case, if all inputs exists I want to receive something like:

SELECT * FROM products WHERE active = 'yes' AND type = 'food' AND created_at > '2016-01-20' AND code = '00856' ORDER BY id DESC

This is the right way to do that? Because I think that every time that i call the ->where method, It'll replace my last ->where.

Thanks a lot! :)

0 likes
3 replies
bobbybouwmann's avatar
Level 88

You need to keep chaining your query like so

$product = Product::where('active', '=', 'yes');
$input = Input::all();

if(isset($input['type'])):
    $product = $product->where('type', '=', $input['type']);
endif;

if(isset($input['date_created'])):
    $product = $product->where('created_at', '>', $input['date_created']);
endif;

if(isset($input['code'])):
    $product = $product->where('code', '=', $input['code']);
endif;

$product->orderBy('id', 'desc')->get();

As you can see I assign the new where statement to the $product variable, if you try it now you will get the full query ;)

2 likes
Rob_vH's avatar

Just a side note, request->input includes has() and get() methods.

Please or to participate in this conversation.