Laravel 5.5 如何在 LaravelCollective Forms 中使用 Foreach 循环

Laravel 5.5 How to use Foreach loop in LaravelCollective Forms

我想以 select 形式使用 foreach 循环。但是我不知道我该怎么做。

我在这里搜索了它,在其他问题中找到了列表方法。但是当我尝试时它会返回 "Call to undefined method App\Category::lists()" 错误。

{{ Form::select('categories',

"foreach loop" for bringing categories

) }}

有什么建议吗?

Laravel Recipes 中所述:

如果你使用这个:

{{ Form::select('age', ['Under 18', '19 to 30', 'Over 30']) }}

您将得到以下输出:

<select name="age">
  <option value="0">Under 18</option>
  <option value="1">19 to 30</option>
  <option value="2">Over 30</option>
</select>

所以在你的情况下你可以这样使用它:

{{ Form::select('categories', $categories->pluck('name')) }}

如果您想将类别的 ID 添加为选项的值,您可以这样做:

在控制器中:

$categories = [''=>''] + Category::lists('name', 'id')->all();
return view('back.create')->withCategories($categories);

并且在视图中:

{{ Form::select('categories', $categories) }}