Hello I have Laravel project, I want filter menu by products category I have in blade this select form which selects food dish how is it cold,hot or something
<div class="form-group">
<label for="">Product Type:</label>
<select class="form-control" name="category" id="">
@foreach ($variety as $cate)
<option value="{{ $cate->menu_categories }}">{{ $cate->menu_categories }}</option>
@endforeach
</select>
</div>
In DB there are food categories: Hot Dish and Cold Dish, when I add it shows like this
<div class="container mt-3">
<div class="row">
@foreach ($uploadProducts as $item)
<div class="col-sm-2 p-0 rounded border mr-2 mb-2 " style="background-color: #fff">
<img src="{{ asset('storage/' . $item->image_upload) }}" alt="..." class="img-fluid rounded w-100">
<p class="h5 text-center mt-2 mb-2">{{ $item->my_products }}</p>
<p class="h6 text-center p-1">{{ $item->my_products_desc }}</p>
<p class="h6 ml-3">
<span class="border rounded mb-2" style="background-color: rgb(48, 225, 28);">{{ $item->full_price }}₾</span>
</p>
</div>
@endforeach
</div>
</div>
and what I add for example pizza which category is Hot dish its also shows in Cold Dish. I want what is cold dish added in cold dish and what is hot added in hot dish table how can I filter it ?
here is my controller
public function index() {
$uploadProducts = Products::orderBy('created_at', 'desc')->get();
$addProducts = AddProducts::all();
$dishes = Dishes::all();
$variety = MenuVariety::all();
return view('Products.products', compact('uploadProducts','dishes','addProducts', 'variety'));
}
Screenshot:Screenshot
I try edit DB also edit controller, for me is important example how to do it.
2
Answers
You want to make filters using the relationship between product and category So you should use whereHas
First, you have to send the ID of the categoy on which you want the use to filter on the client side
Here’s an example code
This is if each product has one category and the filter is based on one category
In the event that each product has more than one category, and to search in many categories, you must use the following
I hope this helps you … good luck
Edit …
First you have to edit the question. You do not ask for filtering, you are asked to fetch the data according to a specific condition
the cold dishes
the hot dishes
you can filter in the same method in the controller using
->when(condition, callback)
, this method apply some query only when the condition istrue
. The code should be something like this:now in the blade you should put the select in a "GET form":
Now you can add a button to submit the form or add script with JS to submit the form every time the select is change with a "change" event.
Don’t forget to validate the form request.