In this tutorial we are going to learn about Filter Products By Brands
So let see how can filter products by brands.
first of all lets display all brands on this shop page here
For that go to the ShopController and inside the index method fetch all brands and return this brands to the view as following


public function index(Request $request)
{

$brands = Brand::orderBy('name','ASC')->get();
return view('shop',['products'=>$products,'page'=>$page,'size'=>$size, 'order'=>$order,'products'=>$products, 'brands'=>$brands]);
}


Now go to the shop.blade.php file here and here lets display the brands


<div class="accordion-item category-rating">
<h2 class="accordion-header" id="headingTwo">
<button class="accordion-button" type="button" data-bs-toggle="collapse"
data-bs-target="#collapseTwo">
Brand
</button>
</h2>
<div id="collapseTwo" class="accordion-collapse collapse show"
data-bs-parent="#accordionExample">
<div class="accordion-body category-scroll">
<ul class="category-list">
@foreach ($brands as $brand)
<li>
<div class="form-check ps-0 custome-form-check">
<input class="checkbox_animated check-it" id="br{{$brand->id}}" name="brands" @if(in_array($brand->id,explode(',',$q_brands))) checked="checked" @endif value="{{$brand->id}}" type="checkbox" onchange="filterProductsByBrand(this)">
<label class="form-check-label">{{$brand->name}}</label>
<p class="font-light">({{$brand->products->count()}})</p>
</div>
</li>
@endforeach

</ul>
</div>
</div>
</div>


Now inside the filter form add a hidden field for brands


<input type="hidden" id="brands" name="brands" value="{{$q_brands}}" />


Now write code for handle the change event


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


Now create a JavaScript function for filter the brand


function filterProductsByBrand(brand){
var brands = "";
$("input[name='brands']:checked").each(function(){
if(brands=="")
{
brands += this.value;
}
else{
brands += "," + this.value;
}
});
$("#brands").val(brands);
$("#frmFilter").submit();
}


Now go to the Shop controller and add here where for filter the filter


public function index(Request $request)
{
$brands = Brand::orderBy('name','ASC')->get();
$q_brands = $request->query("brands");
$products = Product::where(function($query) use($q_brands){
$query->whereIn('brand_id',explode(',',$q_brands))->orWhereRaw("'".$q_brands."'=''");
})
->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]);
}


Now lets check so go the shop page now you can see here all the brands
now lets check on any one brand
And you can you see the products from this brand only
Now lets display here the selected brand
So in this way you can filter products by brand