Laravel Form-Model Binding多选默认值

krs*_*ndm 11 html php binding laravel blade

我正在尝试将默认值绑定到选择标记.(在"编辑视图"中).

我知道这应该很容易,但我想我错过了一些东西.

我有:

User.php(我的用户模型)

...
    public function groups() 
{
    return $this->belongsToMany('App\Group');
}

public function getGroupListAttribute()
{
    return $this->groups->lists('id');
}
...
Run Code Online (Sandbox Code Playgroud)

UserController.php(我的控制器)

...
public function edit(User $user)
{
    $groups = Group::lists('name', 'id');

    return view('users.admin.edit', compact('user', 'groups'));
}
...
Run Code Online (Sandbox Code Playgroud)

edit.blade.php(视图)

...
{!! Form::model($user, ['method' => 'PATCH', 'action' => ['UserController@update', $user->id]]) !!}
...

...
// the form should be binded by the attribute 'group_list' created
// at the second block of 'User.php'
// performing a $user->group_list gets me the correct values
{!! Form::select('group_list[]', $groups, null, [
                                'class' => 'form-control',
                                'id'    => 'grouplist',
                                'multiple' => true
                                ]) !!}
...
Run Code Online (Sandbox Code Playgroud)

我在我的刀片上做了一个虚拟测试,并得到了正确的结果:

@foreach ($user->group_list as $item)
     {{ $item }}
@endforeach
Run Code Online (Sandbox Code Playgroud)

这列出了默认情况下应该选择的值.

我也尝试把它$user->group_list作为第三个参数Form::select,但这没有工作以太......

我不知道我做错了什么..对这个有任何暗示吗?

编辑

当我做:

public function getGroupListAttribute()
{
    //return $this->groups->lists('id');
    return [1,5];
}
Run Code Online (Sandbox Code Playgroud)

该项目已正确选择,

现在我知道我必须从集合中获取数组..深入挖掘.. :)

找到了

user.php的:

...
public function getGroupListAttribute()
{
    return $this->groups->lists('id')->toArray();
}
...
Run Code Online (Sandbox Code Playgroud)

它会更容易吗?

很好的问候,

克里斯托夫

rya*_*ter 2

您不应该放入nullselected defaults第三)参数。

{!! Form::model($user, ['route' => ['user.update', $user->id]]) !!}

{!! Form::select(
        'group_list[]',
        $groups,
        $user->group_list,
        ['multiple' => true]
    )
!!}
Run Code Online (Sandbox Code Playgroud)