I am working on a laravel 8 application and using spatie/laravel-permission for roles and permissions. On the admin page, I'm displaying all users which the admin can do CRUD operations on. The users list also includes his own admin account.
The problem I'm having is when updating user details. The admin can successfully update user account information for other users with validation. However, if the admin tries to edit the information of his own admin account, the validation passes but I get an SQL error :
Integrity constraint violation: 1062 Duplicate entry '[email protected]' for key 'users_email_unique'
See below my UserController
update
method for updating user information with validation:
public function update(Request $request, User $user)
{
$edit_user_rules = array(
// ... other validation rules ...
//'email' => "required|email|unique:users,email,{{$user->id}}", //. auth()->user()->id,
'email' => ['required', 'string', 'email', Rule::unique('users')->ignore($user->id)],
// ... other validation rules ...
);
$validator = Validator::make($request->all(), $edit_user_rules);
if ($validator->fails()) {
Session::flash('failed', 'Failed to save User details!');
return redirect(route('editUser', ['user' => $user->id]))->withErrors($validator)->withInput();
} else {
$validated = $validator->validated();
$updatedUser = User::find($user)->first();
// ... other user fields ...
$updatedUser->username = $validated['username'];
$updatedUser->email = $validated['email'];
// ... other user fields ...
if ($updatedUser->save()) {
return redirect(route('allUsers'));
} else {
return redirect(route('allUsers')); // with errors
}
}
}
I've tried to use different validation rules on the email
field, for example,
"required|email|unique:users,email,{{$user->id}}"
"required|email|unique:users,email," . auth()->user()->id
but none worked. So I used a validation Rule
to validate the unique email field. It works fine when I try to update other users' information but I get the SQL duplicate email error when updating the admin's own account.
Would appreciate any help I can get
CodePudding user response:
You didn't determined which column should be unique to ignore him self.
Change your email validation line to :
'email' => ['required', 'email', Rule::unique('users', 'email')->ignore($user->id)],
Don't forget to put this like to top of your code use Illuminate\Validation\Rule;
.
CodePudding user response:
The error is getting passed the validation rules, but it's failing when it saves the rule. This is because you're not getting the user properly. find()
automatically gets the first record, so first()
is unneeded, and is actually probably pulling the wrong account. When I try User::find(3)->first()
locally, I'm getting user 1 instead of user 3. Remove first()
from your call.
$updatedUser = User::find($user->id);