I've multiple Select
tags in HTML form i.e 'Gender', 'District' etc where the default selection is All
. The eloquent query is dependent on these tags. I can retrieve data from DB if user select an option like Male
or Female
but don't know how to use `All'.
here is html code of Gender
Select tag.
<div class="col-md-2">
<label for="gender">Gender</label>
<select wire:model="byGender" class="custom-select form-control" name="gender" id="gender">
<option selected>All</option>
<option value="male">Male</option>
<option value="female">Female</option>
<option value="combine">Combine</option>
</select>
</div>
and here is Laravel Code
public function mount()
{
$this->rows = DutySheet::where('gender', $this->byGender)->get()->toArray();
}
Note: this is Livewire function and byGender
will be updated as the user select an option.
My question is what to use as value of All
option in Select
tag to retrieve all data from DB, ""
is not working.
Your All
options are represented by empty values (empty strings). You can leverage this by using the when()
method on the query-builder, which effectively is an if-statement - the closure is only applied to the querybuilder if the first parameter is true.
$this->rows = DutySheet::when($this->byGender !== '', function($query) {
return $query->where('gender', $this->byGender)
})
->get()
->toArray();
You can chain these and add as many when()
as you want to your query, to compute a more complex query with conditional conditionals.