In this tutorial we are going to learn about Product Filter By Categories.
So let see how can filter products by category.
first of all lets display all categories on this shop page here
So go to the ShopController
And inside index function lets fetch all categories as following


$categories = Category::orderBy("name","ASC")->get();
$q_categories = $request->query("categories");


Now return this categories to the shop view.
Now go to the shop.blade.php file and here lets display 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>


Now inside the from add the input hidden filed


<input type="hidden" id="categories" name="categories" value="{{$q_categories}}" />


Now write code for handle the change event


<script>
$(function(){
$("#orderby").on("change",function(){
$("#order").val($("#orderby option:selected").val());
$("#frmFilter").submit();
});
});
</script>


Now create a JavaScript function for filtering the product 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 this Check box on change event onchange="filterCategory(this)"

Now its done so lets check it
So switch to the browser and just refresh the page
Now lets click on any category
And her you can see the all products related to this category
Now check another
So lets 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