Laravel 10 E-Commerce Project - Filtering Products by Price
In this tutorial, we will learn about filtering products by price.
Let's explore how to filter products by price.
Setting Up the Price Range in the Shop Controller
Go to the ShopController and inside the index function, create a variable for the price range and assign the value from the query string as follows:
public function index(Request $request)
{
$prange = $request->query("prange");
if(!$prange)
$prange = "0,500";
$from = explode(",",$prange)[0];
$to = explode(",",$prange)[1];
$products = Product::where(function($query) use($q_brands){
$query->whereIn('brand_id',explode(',',$q_brands))->orWhereRaw("'".$q_brands."'=''");
})
->where(function($query) use($q_categories){
$query->whereIn('category_id',explode(',',$q_categories))->orWhereRaw("'".$q_categories."'=''");
})
->whereBetween('regular_price',array($from,$to))
->orderBy('created_at','DESC')->orderBy($o_column,$o_order)->paginate($size);
return view('shop',['products'=>$products,'page'=>$page,'size'=>$size,'order'=>$order,'brands'=>$brands,'q_brands'=>$q_brands,'categories'=>$categories,'q_categories'=>$q_categories,'from'=>$from,'to'=>$to]);
}
Adding a Hidden Field to the Filter Form
Now, go to the shop.blade.php file and add a hidden field in the filter form:
<input type="hidden" name="prange" id="prange" value="" />
Creating a JavaScript Function for Filtering by Price
Now, add a JavaScript function inside the push directive as follows:
<script>
$(function(){
var $range = $(".js-range-slider");
instance = $range.data("ionRangeSlider");
instance.update({
from:{{$from}},
to:{{$to}}
});
$("#prange").on("change",function(){
setTimeout(()=>{
$("#frmFilter").submit();
},1000);
});
});
</script>
Testing the Filtering Functionality
Now, it's done! Let's check it.
Switch to the browser and just refresh the page.
Now, let's slide the price range slider, and here you can see all the products between this price range.
Now, set another price range.
So, in this way, you can filter products by price.