In this tutorial, we will learn about filtering products by categories.
Let's explore how to filter products by category.
Displaying All Categories on the Shop Page
First, let's display all categories on this shop page.
So, go to the ShopController and inside the index function, fetch all categories as follows:
$categories = Category::orderBy("name","ASC")->get();
$q_categories = $request->query("categories");
Now, return these categories to the shop view.
Displaying Categories in the Shop Blade Template
Now, go to the shop.blade.php file and display the categories:
<div class="accordion-item category-rating">
<h2 class="accordion-header" id="headingOne">
<button class="accordion-button" type="button" data-bs-toggle="collapse"
data-bs-target="#collapseSix">
Category
</button>
</h2>
<div id="collapseSix" class="accordion-collapse collapse show"
aria-labelledby="headingOne">
<div class="accordion-body category-scroll">
<ul class="category-list">
@foreach ($categories as $category)
<li>
<div class="form-check ps-0 custome-form-check">
<input class="checkbox_animated check-it" id="ct{{$category->id}}" name="categories" type="checkbox" @if(in_array($category->id,explode(',',$q_categories))) checked="checked" @endif value="{{$category->id}}" onchange="filterProductsByCategory(this)">
<label class="form-check-label">{{$category->name}}</label>
<p class="font-light">({{$category->products->count()}})</p>
</div>
</li>
@endforeach
</ul>
</div>
</div>
</div>
Adding a Hidden Field to the Form
Inside the form, add an input hidden field:
<input type="hidden" id="categories" name="categories" value="{{$q_categories}}" />
Handling the Change Event
Now, write code to handle the change event:
<script>
$(function(){
$("#orderby").on("change",function(){
$("#order").val($("#orderby option:selected").val());
$("#frmFilter").submit();
});
});
</script>
Creating a JavaScript Function for Filtering Products by Category
Now, create a JavaScript function for filtering products by category:
function filterProductsByCategory(brand){
var categories = "";
$("input[name='categories']:checked").each(function(){
if(categories=="")
{
categories += this.value;
}
else{
categories += "," + this.value;
}
});
$("#categories").val(categories);
$("#frmFilter").submit();
}
Now, call this function from the checkbox on the change event: onchange="filterCategory(this)"
Testing the Filtering Functionality
Now, it's done! Let's check it.
Switch to the browser and just refresh the page.
Now, let's click on any category, and here you can see all the products related to this category.
Now, check another category. So, let's click on another category, and here are the products of these categories.
And you can see the filtered categories.
So, in this way, you can filter products by categories.