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

adnan483's avatar

Write complex query with Eloquent

Is possible to do this with query builder:


$query = "SELECT * FROM products WHERE status = 1";

some if statement and concat 

$query .= "AND product_price BETWEEN $request->minimum AND $request->maximum";

again some if and

$brand_filter = implode("','",$request->brand);
$query .= "AND product_brand IN('". $brand_filter."')";

0 likes
4 replies
Cronix's avatar
Cronix
Best Answer
Level 67
$builder = DB::table('products')->where('status', 1);

if (condition) {
    $builder->whereBetween('product_price', [$request->minimum, $request->maximum]);
}

if (condition) {
    $builder->whereIn('product_brand', $request->brand);
}

$result = $builder->get(); // finally, execute the query with get().

It's a builder instance until you execute the query, so you can keep chaining methods on until you execute the query with get() (or first(), etc)

I'd really urge you to look at eloquent models over the query builder though.

adnan483's avatar

@cronix I have in another table sizes and colors is possible to add that table in that query to? Same thing like brand but only size and color from product-stock

adnan483's avatar

@cronix I tried it like this

$products = DB::table('products')->join('product_attributes', 'products.id','=','product_attributes.product_id')->select('products.*', 'product_attributes.*')->where('products.status', 1);
        if (isset($request->minimum_price) && isset($request->maximum_price)) {
            $products->whereBetween('products.price', [$request->minimum_price, $request->maximum_price]);
        }
        if (isset($request->brand)) {
            $products->whereIn('products.brand_id', $request->brand);
        }
        if (isset($request->size)) {
            $products->whereIn('product_attributes.size', $request->size);
        }
        $result = $products->get();

but problem is I have products as many as sizes in attributes table, and distinct is not working in this case

Please or to participate in this conversation.