doukesou4452
2017-11-25 15:03 阅读 18
已采纳

Laravel - 按角色名称编辑角色用户

I have made an edit page for my users and everything works except changing the role. I have made a select menu which displays all the roles through a foreach loop. And it displays the current role of the user like this:

<div class="form-group row">
   <div class="col-md-4">
      <label for="Datum">Rol:</label>
   </div>
   <div class="col-md-8">
     <select class="form-control" id="Datum" name="role">
       <option selected>{{ $user->role->role_name }}</option>
       @foreach($roles as $role)
       <option>{{ $role->role_name }}</option>
       @endforeach
     </select>
   </div>
  </div>

I want to be able to change the role by the role_name instead of ID. I honestly don't know where to look. How can I achieve this?

The controller that the form goes through looks like this:

public function updateUser(Request $request, $id)
{

    $user = User::find($id);
    $user->update($request->all());
    $user->save();

    return back()->with('flash', 'Account is geupdate');
}

In the database, a user has a role_id and in the role table, it has all the roles. So the relations are: User has a Role, Role has many users. These relations are set in the models. So {{ $user->role->role_name }} works just fine.

Thanks in advance!

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享

1条回答 默认 最新

  • 已采纳
    dqf35839 dqf35839 2017-11-25 15:19

    Assume role_name is unique. In your post method you can do the following-

    public function updateUser(Request $request, $id)
    {
            $role = Role::where('role_name','=',$request->input('role_name'))->first();
            $user = User::find($id);
            $user->role_id = $role->id;
            $user->save();
    
           return back()->with('flash', 'Account is geupdate');
    }
    

    As per your comment, add this on your user model-

     public function setPasswordAttribute($password)
    {   
        $this->attributes['password'] = bcrypt($password);
    }
    

    Hope it helps :)

    点赞 评论 复制链接分享

相关推荐