I am using a resource controller UserController
, with routes defined like:
Route::group([
'middleware' => 'can:admin-user',
'prefix' => 'admin',
], function(){
Route::resource('user', 'Admin\UserController');
});
And an update function defined (by Laravel make) like:
public function update(Request $request, User $user)
{
$validator = Validator::make($request->all(), [
'email' => [
'required',
'string',
'email',
'max:255',
Rule::unique('users')->ignore($user->id)
],
'password' => ['sometimes', 'string', 'min:6'],
'role' => ['sometimes', 'array'],
'role.*' => ['sometimes', Rule::in(Role::all()->pluck('id')->toArray())],
'permission' => ['sometimes', 'array'],
'permission.*' => ['sometimes', Rule::in(Permission::all()->pluck('id')->toArray())],
]);
if ($validator->fails()) {
return redirect()
->route('user.edit', ['user' => $user])
->withErrors($validator)
->withInput();
}
$data = $validator->validated();
foreach ($data as $k => $v) {
if ($k === 'password') {
$user->password = Hash::make($data['password']);
} elseif($k === 'role') {
$user->roles()->sync($v);
}elseif($k === 'permission'){
$user->permissions()->sync($v);
} else {
$user->$k = $v;
}
}
$user->save();
Flash::success(__('User updated'));
return redirect()
->route('user.edit', ['user' => $user]);
}
If I edit any user except the one logged in it works just fine, but if I edit the current user it logs me out.
Where it breaks, specifically, is changing any of the User
model attributes, if I just save the user without changing email or password it works, or if I just sync relations it works (so it is only a dirty model that causes it).
Weirdly, I have another action that works if I go on $request->user()
.
I have tied to find out why but haven't got far (Laravel noob).
Why is this?
via Chebli Mohamed
Aucun commentaire:
Enregistrer un commentaire