doukesou4452 2017-11-25 15:03
浏览 37
已采纳

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 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 :)

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3
  • ¥15 牛顿斯科特系数表表示
  • ¥15 arduino 步进电机
  • ¥20 程序进入HardFault_Handler