Laravel Blade 如何设置下拉列表的选项
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24708260/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
laravel blade how to set the options for drop down list
提问by Anastasie Laurent
I am trying to create an drop down list using blade
我正在尝试使用创建一个下拉列表 blade
I have already checked this question Laravel 4 blade drop-down list class attribute
我已经检查过这个问题Laravel 4 Blade 下拉列表类属性
I tried this:
我试过这个:
{{Form::select('category_id', $categories)}}
and the result is:
结果是:
<select name="category_id"><option value="0">{"id":2,"name":"Apartment"}</option><option value="1">{"id":3,"name":"Car"}</option></select>
I couldn't know how to show just the name
value of the options. plus I couldn't know how to set the value of each option to its id
我不知道如何只显示name
选项的价值。另外我不知道如何将每个选项的值设置为其id
I know the forth parameter is the option one, and I tried to do this
我知道第四个参数是选项之一,我尝试这样做
{{Form::select('category_id', $categories, '', $categories)}}
but I got this exception:
但我得到了这个例外:
htmlentities() expects parameter 1 to be string, array given (View:
please notice that the $categories
is array, each row has id
andname
请注意$categories
is 数组,每一行都有id
和name
Update 1
更新 1
I send the value from controller to view like this
我将值从控制器发送到这样查看
$categories = Category::All(['id', 'name']);
where Category
is a model
Category
模型在哪里
回答by peterm
Form::select()
requires a flat array like
Form::select()
需要一个平面阵列,如
array( 1 => 'Appartment', 2 => 'Car' )
whereas $categories = Category::all()
gives you a multidimensional array that looks like
而$categories = Category::all()
给你一个多维数组,看起来像
array( 0 => array( 'id' => 1, 'name' => 'Appartment' ), 1 => array( 'id' => 2, 'name' => 'Car' ) )
That being said just change
话虽这么说只是改变
$categories = Category::all(['id', 'name']);
to
到
$categories = Category::lists('name', 'id');
Then this will work just fine
然后这将工作得很好
{{ Form::select('category_id', $categories) }}