如何在 laravel 中的 blade 中将 optgroup 与数组一起使用

how to use optgroup with array in blade in laravel

如何在 laravel 5.3 中的 blade 中对数组使用 optgroup?

我在我的项目中使用 select2

例如:

<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>

Controller中:

public function index()
{
    $airport = Airport::where('status', 1)->pluck('city', 'iata');
    return view($this -> path_site_theme() . '.home.index', ['airport' => $airport]);
}

index.blade.php中:

{{ Form::select('from', ['Top Airport' => ['MHD', 'Mashhad', 'THR' => 'Tehran'], 'All Airport' => $airport], null, ['class' => 'form-control select2']) }}

pluck 方法 return Collection 的一个实例,而 Form::select() 需要一个数组。您可以在 pluck 上链接 toArray() 方法以使其工作。

$airport = Airport::where('status', 1)->pluck('city', 'iata')->toArray();

或者更好的是,如果您使用 PHP7,请使用合并运算符。它永远不会失败,即使数据库中没有活动机场,当 toArray() 尝试将 null 转换为数组时经常发生这种情况。

$airport = Airport::where('status', 1)->pluck('city', 'iata')->toArray() ?? [];