how to use optgroup with array in blade in laravel 5.3?
I use select2 in my project.
For Example:
<select class="form-control select2">
<optgroup label="Top Airport">
<option value="MHD">Mashhad</option>
<option value="THR">Tehran</option>
</optgroup>
<optgroup label="All Airport">
<option value="MHD">Mashhad</option>
<option value="THR">Tehran</option>
<option value="LON">London</option>
.
.
.
</optgroup>
</select>
In Controller
:
public function index()
{
$airport = Airport::where('status', 1)->pluck('city', 'iata');
return view($this -> path_site_theme() . '.home.index', ['airport' => $airport]);
}
In index.blade.php
:
{{ Form::select('from', ['Top Airport' => ['MHD', 'Mashhad', 'THR' => 'Tehran'], 'All Airport' => $airport], null, ['class' => 'form-control select2']) }}
The pluck
method return an instance of Collection
while the Form::select()
expects an array. You can chain toArray()
method on pluck to make it work.
$airport = Airport::where('status', 1)->pluck('city', 'iata')->toArray();
Or better, use coalescing operator if you are using PHP7. It will never fail even if there's no active airports in database which happens a lot with toArray()
when it tries to convert null into an array.
$airport = Airport::where('status', 1)->pluck('city', 'iata')->toArray() ?? [];