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."')";
$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.
@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
@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 sign in or create an account to participate in this conversation.