Laravel 8 E-Commerce - Add Price Filter On Shop Page
In this video, we will learn about adding a price filter on the shop page.
Let's see how we can add a price filter on the shop page. For adding a price filter, we will use the noUiSlider.
First, let's add the noUiSlider CDN to our project. Switch to the browser and open a new tab. Search for "noUiSlider CDN" on Google.
Click on the link for the noUiSlider CDN and copy the noUiSlider.min.js and nouislider.min.css files. First, copy the nouislider.min.css file and paste it inside the head part of the base.blade.php file. Then, paste the noUiSlider.min.js CDN at the bottom of the page.
Now, go to the ShopComponent.php class file and create two properties:
public $min_price = 1;
public $max_price = 1000;
Now, let's make changes in the render method as follows:
public function render()
{
if($this->sorting=='date')
{
$products = Product::whereBetween('regular_price',[$this->min_price,$this->max_price])->orderBy('created_at','DESC')->paginate($this->pagesize);
}
else if($this->sorting=="price")
{
$products = Product::whereBetween('regular_price',[$this->min_price,$this->max_price])->orderBy('regular_price','ASC')->paginate($this->pagesize);
}
else if($this->sorting=="price-desc")
{
$products = Product::whereBetween('regular_price',[$this->min_price,$this->max_price])->orderBy('regular_price','DESC')->paginate($this->pagesize);
}
else{
$products = Product::whereBetween('regular_price',[$this->min_price,$this->max_price])->paginate($this->pagesize);
}
$categories = Category::all();
return view('livewire.shop-component',['products'=> $products,'categories'=>$categories])->layout("layouts.base");
}
After this, go to the shop-component.blade.php view file and add the following code inside the sidebar:
<div class="widget mercado-widget filter-widget price-filter">
<h2 class="widget-title">Price <span class="text-info">${{$min_price}} - ${{$max_price}}</span></h2>
<div class="widget-content" style="padding:10px 5px 40px 5px;">
<div id="slider" wire:ignore></div>
</div>
</div>
Now, in this view file, go to the bottom of the page and add the following code:
@push('scripts')
<script>
var slider = document.getElementById('slider');
noUiSlider.create(slider,{
start : [1,1000],
connect:true,
range :{
'min' : 1,
'max' : 1000
},
pips:{
mode:'steps',
stepped:true,
density:4
}
});
slider.noUiSlider.on('update',function(value){
@this.set('min_price',value[0]);
@this.set('max_price',value[1]);
});
</script>
@endpush
Now, everything is set up. Let's check it. Switch to the browser and refresh the page.
Now, let's slide the price slider. You can see the price range, which is the minimum price and the maximum price. You can also see the products that are within this price range.
If you set the minimum price to this and the maximum price to that, you can see the products that are within this price range.
So, in this way, you can add a price filter on the shop page.