[英]Laravel - Edit role user by role_name
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.
我做了一个选择菜单,该菜单通过一个foreach循环显示所有角色。 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. 我希望能够通过role_name而不是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. 在数据库中,用户具有role_id,在角色表中,它具有所有角色。 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. 因此
{{ $user->role->role_name }}
可以正常工作。
Thanks in advance! 提前致谢!
Assume role_name is unique. 假设role_name是唯一的。 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 :) 希望能帮助到你 :)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.