【问题标题】:how to use optgroup with array in blade in laravel如何在 laravel 的刀片中使用 optgroup 和数组
【发布时间】:2017-01-26 04:09:03
【问题描述】:

如何在 laravel 5.3 的刀片中使用 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']) }}

【问题讨论】:

  • 有什么问题? Form::select() 没有给你预期的输出吗?

标签: laravel laravel-5.3 laravel-blade


【解决方案1】:

pluck 方法返回一个 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() ?? [];

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-01-21
    • 1970-01-01
    • 2019-07-29
    • 2016-06-24
    • 2021-07-07
    • 1970-01-01
    • 2017-11-08
    • 2021-07-06
    相关资源
    最近更新 更多