Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Zabius's avatar

Validation problem on edit with duplicated email addresses (unique values required)

I am building a CMS system, where an admin can add a new user to the system fine (name, email etc..). When I am trying to edit a user the issue I get is if a user being edited by the admin uses an existing email address in the database I get the following MySQL error.

Integrity constraint violation: 1062 Duplicate entry '[email protected]' for key 'users_email_unique'

I want to have the error gracefully to the Laravel errors array rather than an Exception, so it would use the validation to use some custom logic which checks if the email exists if so to have an error 'email already exists to another user'

Can anyone suggest how I should do this?

public function store(Request $request)
{
    $this->validate($request, [
        'email' => 'required|email|unique:users'
    ]);
}
0 likes
1 reply
pawelmysior's avatar
Level 15

You have to tell the Validator to ignore the currently edited user's id when it check the uniqueness of the email. Laravel allows you to do that like this:

use Illuminate\Validation\Rule; // don't forget to import this class at the top of your file

public function store(Request $request)
{
    $this->validate($request, [
        'email' => [
            'required',
            'email',
            Rule::unique('users')->ignore($userId),
    ]);
}

Read about it in the documentation: https://laravel.com/docs/5.4/validation#rule-unique

You can also define it using a string, which would look something like this:

'email' => "unique:users,email,{$userId}"

IMPORTANT NOTE: If you're updating the user the name of the controller method shouldn't be store. It should be update.

2 likes

Please or to participate in this conversation.