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

lat4732's avatar
Level 12

Handling duplicate key value violates unique constraint error

Hey!

When trying to register with an email that exists in the database I'm getting the following error:

SQLSTATE[23505]: Unique violation: 7 ERROR: duplicate key value violates unique constraint "users_email_unique" DETAIL: Key (email)=([email protected]) already exists.

how can I change this error page to appear as a validation error (alert) and not a query exception? Something like: This email has already been registered

Here's my validation inside app/Actions/Fortify/CreateNewUser.php

Validator::make($input, [
            'name' => ['required', 'string', 'max:255'],
            'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
            'password' => $this->passwordRules(),
            'terms' => Jetstream::hasTermsAndPrivacyPolicyFeature() ? ['required', 'accepted'] : '',
            'g-recaptcha-response' => 'required|recaptcha',
        ],
        [
            'g-recaptcha-response.required' => 'The robot check is required.',
            'g-recaptcha-response.recaptcha' => 'Captcha verification failed!'
        ])->validate();
0 likes
17 replies
tykus's avatar

How is this not being caught by validation? How are you actually trying to create the User?

lat4732's avatar
Level 12

@tykus with the Laravel's out of box route

<form method="POST" action="{{ route('register') }}" autocomplete="off">
      // ...
</form>

The app is not in production (APP_ENV=local)

tykus's avatar

@Laralex out of the box; the unique validation rule should be catching the duplicate email address. Is there a custom action that implements CreatesNewUsers interface that is being executed in place of the default CreateNewUser action? Are you actually hitting that create method?

lat4732's avatar
Level 12

@tykus The problem might be that I'm using postgreSQL according to this thread. I haven't created anything that implements CreatesNewUsers interface. I'm hitting that create method because I added 2 custom columns to the users table and it's properly working.

return User::create([
                'name' => $input['name'],
                'email' => strtolower($input['email']),
                'password' => Hash::make($input['password']),
                'bgColor' => $arr[$rand]['background'],
                'textColor' => $arr[$rand]['text'],
            ]);
lat4732's avatar
Level 12

@tykus The current solution that is in the thread I shared is working fine according to my tests. So what can we do to handle this error more beautifully?

lat4732's avatar
Level 12

@tykus I think there is some misunderstanding.. Imagine we have a registered user with [email protected] email. When I try to register with [email protected] I'm getting a error page

SQLSTATE[23505]: Unique violation: 7 ERROR: duplicate key value violates unique constraint "users_email_unique" DETAIL: Key (email)=([email protected]) already exists. (SQL: insert into "users" ("name", "email", "password", "bgColor", "textColor", "updated_at", "created_at") values (haha, [email protected], y$WcqgaSbBnDLnS8KCFF2LxOhr6Fy8DfZ98l0Vson1T07y0aWvkz5ga, #159de1, #ffffff, 2022-04-04 13:35:48, 2022-04-04 13:35:48) returning "id") 

and that's not what I want. I want the user to be shown an alert just like the validation error messages

vis

I have no idea why but the Unique violation: 7 error is shown only when I try to register with already existing email but with a uppercase letter changed. If in the database exists [email protected] and I try to register with [email protected] I'm getting the error. When I try to register with just [email protected] I'm getting the image I shown above. Why is that happening?

////////////////////////////////////////////////////////////////

UPDATE

The Unique violation: 7 is showing after I did the things that we discussed here. Before that I was able to register with a existing email with just changed uppercase letter.

tykus's avatar

@Laralex - I don't know; never experienced this so testing locally here...

etiennedeschenes's avatar

Hello,

Use this in your validation rules:

[
	'email' => 'required|email|unique:users,email'
]

Hope it helps!

lat4732's avatar
Level 12

@sr57 Oh, you're right... so I need to convert input in lower case before validation? But how to do it the best way?

Please or to participate in this conversation.