Laravel从模型中获得多项选择

时间:2017-05-18 15:28:55

标签: php laravel

我在多对多关系中定义了User Role个模型。创建用户时,我有一个多选框,可以为特定用户选择角色:

<div class="col-lg-6 col-md-6 col-sm-6 col-xs-6">
    <div class="form-group">
        <label for="roles">Roles</label>
        {!! Form::select('roles[]',$roles, null,['class' => 'form-control selectpicker','multiple' => 'true']) !!}
    </div>
</div>

这是一个在创建和编辑方法中共享的表单,但对于编辑,它是这样的:

{!! Form::model($patient, ['route' => ['patients.update', $patient->id], 'method' => 'PUT']) !!}
    @include('patients.partials.form')
{!! Form::close()!!}

当我尝试使用角色编辑用户时,没有选择角色......这是控制器

public function edit(User $user)
{
    $clinics = Clinic::pluck('name', 'id');
    $roles = Role::pluck('display_name', 'id');
    $states = State::pluck('name', 'id');
    $cities = City::pluck('name', 'id');
    return view('users.edit', compact('user', 'clinics', 'states', 'cities', 'roles'));
}

修改

我处理这样的更新:

public function update(Request $request, User $user)
{
    if ($request->has('password'))
        $user->update($request->except('password_confirmation'));
    else
        $user->update($request->except('password', 'password_confirmation'));

    $user->roles()->sync($request->roles);
    return redirect('users')->with('status', 'User Updated!');
}

请求转储的一部分:

"roles": [
    "1",
    "4"
],
"first_name": "xy",
"last_name": "yx",

1 个答案:

答案 0 :(得分:1)

表单select的第三个参数采用所选的item数组。对所选角色进行以下更改,以便在编辑时显示。

// Pass the current user roles
public function edit(User $user)
{
    $userRoles = $user->roles->pluck('id');
    $clinics = Clinic::pluck('name', 'id');
    $roles = Role::pluck('display_name', 'id');
    $states = State::pluck('name', 'id');
    $cities = City::pluck('name', 'id');
    return view('users.edit', compact('user', 'userRoles', 'clinics', 'states', 'cities', 'roles'));
}

// Pass the selected list of roles 
{!! Form::model($patient, ['route' => ['patients.update', $patient->id], 'method' => 'PUT']) !!}
    @include('patients.partials.form', ['selected' => $userRoles])
{!! Form::close()!!}

// Check if a selected value is given and use it. This makes it reusable with create and edit.
{!! Form::select('roles[]', $roles, isset($selected) ? $selected : null, [
    'class' => 'form-control selectpicker',
    'multiple' => 'true'
]) !!}