【发布时间】:2013-01-08 18:14:51
【问题描述】:
我正在尝试使用 Laravel 生成一个包含来自 MySQL 表的值的下拉列表。该表很简单,两列 - id 和 category。
以下将检索所有记录(类别)但返回一个对象而不是数组,这是我需要的下拉代码 -
$categories = Category::all();
下拉的代码是:
{{ Form::select('category', $categories, $post->category_id) }}
想法?
更新
bgallagh3r 建议使用 foreach 循环将每个类别转换为数组。他们的代码让我很接近,但生成了一堆时髦的嵌套optgrouptags。我能把它降到只有一个 optgroup 但那太多了..
$categories = Category::all();
foreach ($categories as $cat)
{
$category = $cat->to_array();
$id = $category['id'];
$value = $category['category'];
$cats[] = array($id => $value);
}
然后,格式为:
{{ Form::select('categories', $categories)}}
我最终得到了这个 HTML:
<select name="categories">
<optgroup label="0">
<option value="1">Department News</option>
</optgroup>
<optgroup label="1">
<option value="2">General</option>
</optgroup>
...
</select>
【问题讨论】: