Foreach inside a Form::select in Laravel 4

我只是一个虾纸丫 提交于 2019-12-03 21:55:36
Gareth Daine

Use the lists() method and pass that to your Form::select() method. Like so:

$categories = Category::lists('name', 'id');

In your view:

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

for you want to use foreach laravelcollective in laravel 5.2 or above, you can use same as @garethDaine but above laravel 5.2, you using pluck() instead lists() because lists() function was depracated in laravel 5.2.

so in the examples is:

$banks = Bank::pluck('name', 'id'); 

instead

$banks = Bank::lists('name', 'id');

then in your view form:

{!! Form::select('bank_id', $banks, null, ['class' => 'form-control']) !!}

Note: 1st array in you pluck() will be name display on you <option> and second will be value="1" as example.

In case you want to add a default value also to your options you need to do this:

$categories = Category::lists('name', 'id')->toArray();

In your view:

{{ Form::select('category_id', array('0' => 'Default') + $categories) }}

The answer by Gareth Daine edited by Drew Hammond worked for me, with a slight edit

My Controller

$category = Category::all();

My View

{!! Form::select('category_id', $categories->pluck('name', 'id')) !!}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!