在我的项目中,我有角色和权限,并且我为用户创建了一个控制器,以便他们可以编辑他们的个人资料,因为usercontroller仅限于管理员角色。
现在我的问题是,当用户更新他的个人资料时,他的角色访问将被分离。 如果用户能够在不改变角色的情况下编辑自己的个人资料,我该怎么办?
这是我的更新功能:
public function update(Request $request, $id)
{
$user = User::findOrFail($id); //Get role specified by id
//Validate name, email and password fields
$this->validate($request, [
'name'=>'required|max:120',
'username'=>'required|max:120',
'email'=>'required|email|unique:users,email,'.$id,
'password' => 'nullable|string|min:6|confirmed'
]);
$input = $request->only(['name', 'username', 'email']); //Retreive the name, email and password fields
if (trim(Input::get('password')) != '') {
$user->password = Hash::make(trim(Input::get('password')));
}
$user->fill($input)->save();
return view('users.profile')
->with('flash_message',
'Your Profile successfully edited.');
}
用户模型:
protected $fillable = [
'name', 'username', 'email', 'password', 'affiliate_id', 'referred_by',
];
数据库:
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('username')->unique();
$table->string('email')->unique();
$table->string('password');
$table->string('referred_by')->nullable();
$table->string('affiliate_id')->unique();
$table->rememberToken();
$table->timestamps();
});
}
答案 0 :(得分:0)
您可以在编辑视图中传递用户的角色,如果它是管理员,您将显示角色复选框或您使用的任何内容,如果不是管理员,您将不会显示角色。
public function edit(Request $request, $id)
{
$user_role = User::findOrFail($id)->roles->toArray();
return view('UserCRUD.edit')->with('user_role', $user_role);
}
在视野中
@if($user_role == 'admin')
<label>
<input type="checkbox" name="role[]" value="value">
</label>
@endif
如果你显示角色,那么只有他们会在$request->all()
数组中
如果我dd($request->all())
而没有在视图中显示角色
array:8 [▼
"_method" => "PATCH"
"_token" => "8xxRjgKaJNlJOwZZ2vZYecs6GrEWjpYqbCtWULJO"
"username" => "testcase1"
"email" => "test1@test.com"
"password" => ""
"confirm_password" => ""
"firstname" => "Test"
"lastname" => "One"
]
如果我dd($request->all())
在视图中显示角色
array:9 [▼
"_method" => "PATCH"
"_token" => "8xxRjgKaJNlJOwZZ2vZYecs6GrEWjpYqbCtWULJO"
"username" => "testcase1"
"email" => "test1@test.com"
"password" => ""
"confirm_password" => ""
"firstname" => "Test"
"lastname" => "One"
"role" => array:1 [▼
0 => "2"
]
]
在更新时,您只需要检查是否设置了角色,而不是更新它们。
$user = User::findOrFail($id);
$user->update($request->all());
if (isset($request->all()['role'])) {
$user->roles()->sync($request->all()['role']);
}