In Dropdown Laravel Blade show option in optgroup based upon a field in the table

Issue

I have a table which screenshot is attached below
database image

I want to show all the Account Type and but it should be shown in option group

select image

How can I achieve this???

dropdown image

Solution

The Laravel helper function groupBy() will help you solve this problem.
Data grouping example:

$cars = Car::where('status', 1)->get();
    
$carModels = $cars->groupBy('model');

Blade example:

<select name="car_id">
    @foreach($carModels as $model => $cars)
    
      <optgroup label="{{ $model }}">
        @foreach($cars as $car)
          <option value="{{ $car->id }}">{{ $car->name }}</option>
        @endforeach
      </optgroup>
    
    @endforeach
</select>

Answered By – Etibar

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published