我正在学习Laravel,并且在尝试将模型的属性绑定到选择标签的选定值时遇到问题。我试图将第三个参数保留为 null,因为我相信表单模型绑定会自动处理它,但它不起作用。这是我已经尝试过的:
{{$article->tag_list}} // show [1,3]
//it doesn't work
{!! Form::select('tag_list[]', $tags, null , ['class' => 'form-control', 'multiple'] ) !!}
-------------
//it doesn't work as well
{!! Form::select('tag_list[]', $tags, $article->tag_list , ['class' => 'form-control', 'multiple'] ) !!}
-----------
//it works
{!! Form::select('tag_list[]', $tags, [1,3] , ['class' => 'form-control', 'multiple'] ) !!}
在模型中,我有工作正常的getTagListAttribute()
。
public function getTagListAttribute(){
return $this->tags->lists('id');
}
使用文本输入,表单工作正常。顺便说一句,我使用的是 5.2.1 版本。我在这里错过了什么?
我找到了缺失的部分。 select
函数需要一个数组,但getTagListAttribute()
返回一个集合对象。
public function getTagListAttribute(){
return $this->tags->lists('id')->all();
}
or I can do this
public function getTagListAttribute(){
return $this->tags->lists('id')->toArray();
}