我希望能够为我的关系生成一个带有"optgroups"的表单选择。
此代码有效:
foreach($old_project as $project)
{
foreach ($project->units as $unit)
{
$new_project[$project->name][] = $unit->name;
}
}
那么在我看来:
{{ Form::select('units', $new_project) }}
但这似乎不对。我试着做$old_project->toArray(),但也不起作用。
我看了这个论坛的帖子,所以我也试着做了->list(),但我似乎无法让它发挥作用。
在Laravel 4中有更好的方法吗?
编辑:
这是我的最终目标——类似这样:
<select id="optgroup3" name="unit">
<optgroup label="Project1">
<option value="1">Option 1</option>
<option value="2">Option 2</option>
</optgroup>
<optgroup label="Project2">
<option value="3">Option 3</option>
<option value="4">Option 4</option>
</optgroup>
</select>
p.s.如果可以避免的话,我不想这样做——我想使用Form::select()并保持它的清洁:
<select id="optgroup3" name="unit">
@foreach($units as $project)
<optgroup label="{{{ $project->name }}}">
@foreach($project->units as $unit)
<option value="{{{ $unit->id }}}">{{{ $unit->name }}}</option>
@endforeach
</optgroup>
@endforeach
</select>
我认为您想要的命令实际上是lists()
。尝试:
Project::lists('name', 'id')