将表单选项更改为 Laravel Collective

Change form option to Laravel Collective

我在我的项目中使用 Laravel 7 和 https://laravelcollective.com/docs/6.0/html#drop-down-lists

我有这个代码:

<select name="category_id" class="form-control w-auto" required="required">
                                    <option value=""></option>
                                    @foreach($categories as $category)
                                        <option value="{{ $category['id'] }}"
                                                @if(isset($product) && $product->category_id
                                                == $category['id']) selected="selected"
                                            @endif>{{ $category['name'] }}
                                        </option>
                                    @endforeach
                                </select>

我想改成Laravel集体。

在 $categories 中我有:

array:19 [▼
  0 => array:2 [▼
    "id" => 1
    "name" => "- Books"
  ]
  1 => array:2 [▼
    "id" => 2
    "name" => "-- Comic Book"
  ]
  2 => array:2 [▶]
  3 => array:2 [▶]
  4 => array:2 [▶]
  5 => array:2 [▶]
  6 => array:2 [▶]
  7 => array:2 [▶]
  8 => array:2 [▶]
  9 => array:2 [▶]
  10 => array:2 [▶]
  11 => array:2 [▶]
  12 => array:2 [▶]
  13 => array:2 [▶]
  14 => array:2 [▶]
  15 => array:2 [▶]
  16 => array:2 [▶]
  17 => array:2 [▶]
  18 => array:2 [▶]
]

(工作正常)。

现在在我的 blade 中,我正在尝试让我的 select/option:

<div class="form-group row">
                            {{Form::label('category_id', 'Kategoria produktu', ['class'=>'col-form-label text-left col-lg-3 col-sm-12'])}}
                            <div class="col-lg-9 col-sm-12">
                                {{ Form::select('category_id', $categories, data_get($product ?? 0, 'category_id') == '0', ['placeholder' => 'Wybierz kategorię', 'required' => 'required', 'class'=>'form-control w-autos']) }}
                            </div>
                        </div>

结果我有这个:https://ibb.co/0Qj4v7k (with collective) not correct select, and correct: https://ibb.co/HC2VCxz(没有集体)

如何修复?

您正在使用 wrong format 传递给 select 方法的数据。需要一个数组,其中key代表option标签的value属性,value代表里面的文字:

[
    1 => '- Books',
    2 => '-- Comic Book",
    // ...
]

您可以使用 $categories 数据库集合上的 pluck method 轻松生成此文件:

$categories->pluck('name', 'id');