Laravel。编辑有关系的用户

时间:2017-08-16 14:03:40

标签: php laravel

我想要表单编辑用户。目前我可以编辑用户表中的数据,但我想从表角色(下拉列表)中为用户角色分配权力。

控制器

public function index()
{
    $users = User::with('roles')->get();
    return view('pages.user', compact('users'));
}
public function update($id, Request $request)
{
    $user = User::with('roles')->findOrFail($id);
    $user->update($request->all());
    return redirect('users');
}

表格

{!! Form::model($user, ['method' => 'PATCH', 'action'=>['UsersController@update', $user->id]]) !!}
            <div class="form-group">
                <div class="form-group">
                    {!! Form::label('name','Name: ') !!}
                    {!! Form::text('name', null, ['class'=>'form-control','placeholder'=>'Here, user name']) !!}
                </div>
                <div class="form-group">
                        {!! Form::label('roles','Roles: ') !!}
                        {!! Form::select('roles',['class'=>'form-control']) !!}
                        {!! Form::select('roles',$user,null,['class'=>'form-control']) !!} 
//i try this but still not working
                </div>
            </div>

寻求帮助。

1 个答案:

答案 0 :(得分:1)

我认为您希望将所有角色展示到角色&#39; droppdown,检查下面的代码更改: 的控制器

public function index()
{   
    //Get user detail
    $users = User::with('roles')->get();

    //Get all roles
    $userRole = Roles::lists('name','id');
    return view('pages.user', compact('users', 'userRole'));
}

<强>表格

<div class="form-group">
    {!! Form::label('roles','Roles: ') !!}
    {!! Form::select('roles',$userRole, null,['class'=>'form-control']) !!}<!-- replace with $users['role_id'], if want to display selected role-->
</div>

注意:使用pluck代替laravel&gt; = 5.3的列表。 Collection,query builder和Eloquent查询构建器对象上的lists方法已重命名为pluck。方法签名保持不变。

让我知道是否还没有工作!