I’m trying to filter some products by categories using the Dropdown. The filter worked very well, but the category in the Dropdown only showed the categories result, e.g there’s a Coffee, and Tea category, if I select Tea, the dropdown only showed the Tea category, unlike before, showing every category available.
Controller :
if(request()->category_filter){
$resultCategory = request()->category_filter;
$products = Product::where('category_id', $resultCategory)->with(['category', 'image'])->get();
}else{
$products = Product::with(['category', 'image'])->get();
}
return view('home.products', compact('products'));
View :
@extends('home.layouts.app')
@section('page-content')
<section class="section-padding" id="products">
<div class="container">
<div class="row">
<div class="col-12">
<h2 class="mb-5 text-center">Products</h2>
</div>
<div class="col-2 filter mb-3 text-center">
<div class="row">
<p>Category</p>
<div class="col">
<form action="{{ route('homepage.products') }}" method="get">
<select name="category_filter" id="category_filter" class="form-select mb-2">
@foreach ($products as $p)
<option value="{{ $p->category->id }}">{{ $p->category->name }}</option>
@endforeach
</select>
<button type="submit" class="btn btn-primary btn-sm"><i class="fas fa-search"></i> Search</button>
<a href="{{ route('homepage.products') }}" class="btn btn-dark btn-sm"><i class="fas fa-arrow-rotate-left"></i> Reset</a>
</form>
</div>
</div>
</div>
<div class="row">
@foreach ($products as $p)
<div class="col-3">
<div class="portfolio-thumb mb-5">
@foreach ($p->image as $image)
<a href="{{ asset('storage/'.$image->path) }}" class="image-popup">
<img src="{{ asset('storage/'.$image->path) }}" class="img-fluid portfolio-image" alt="">
</a>
@break
@endforeach
<div class="portfolio-info">
<h5 class="text-black">{{ $p->name }}</h5>
<h6 style="color:{{ $p->category->indicator }};">{{ $p->category->name }}</h6>
</div>
</div>
</div>
@endforeach
</div>
</div>
</div>
</section>
@endsection
>Solution :
You should query the categories separately from the products, so when you filter the products, the category list will not be affected.
if (request()->category_filter) {
$resultCategory = request()->category_filter;
$products = Product::where('category_id', $resultCategory)->with(['image'])->get();
} else {
$products = Product::with(['image'])->get();
}
$categories = Category::whereHas('products')->get();
return view('home.products', compact('products', 'categories'));
Then in your blade, just loop the $categories variable
<select name="category_filter" id="category_filter" class="form-select mb-2">
@foreach ($categories as $category)
<option value="{{ $category->id }}">{{ $category->name }}</option>
@endforeach
</select>