Home > Software engineering >  Laravel Query depend on Multiple HTML Select tags
Laravel Query depend on Multiple HTML Select tags

Time:07-13

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 >
        <label for="gender">Gender</label>
        <select wire:model="byGender"  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.

  • and "" is not working.

CodePudding user response:

You can add some logic to only apply the where condition when the select menu is set to any value other than "All".

If the user selects male, female or combine then the where condition will be run against that value, otherwise the query will return every record.

public function mount()
{
    $dutySheets = DutySheet::query();
    
    if ($this->byGender !== 'All') {
        $dutySheets->where('gender', $this->byGender);
    }

    $this->rows = $dutySheets->get()->toArray();
}

CodePudding user response:

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.

  • Related