Edmund Sulzanok
Edmund Sulzanok

Reputation: 1973

Duplicate entry '' for key 'users_email_unique' empty field

I have two types of users - real and fake. Fake users are employees, that don't use the system. Real users use their email address to login. So my users migration has $table->string('email')->unique();.

The problem is that fake users may not have an email address. I can add first fake user no problem, but the second one generates error SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '' for key 'users_email_unique'.

What should I do?

Upvotes: 4

Views: 17644

Answers (3)

kamasuPaul
kamasuPaul

Reputation: 323

enter image description here

For any other person who might be looking for a solution in 2020

Look for the this indexes on the users table in phpmyadmin.

Deleting the user_up_number_unique index might solve the problem

Upvotes: 0

Scott
Scott

Reputation: 1922

Sounds like users_email_unique is your primary key. This means that when you insert your first fake user with a blank email address, the blank entry is counted as a unique entry. When your second blank entry is entered it violates entity integrity (duplicate primary keys).

users_email_unique    unique?
_________________     _______
[email protected]       yes
blank                 yes
blank                 no

If you want multiple blank entries you could allow users_email_unique to be null, however, a primary key column cannot contain null values:

users_email_unique   unique?
__________________   ________
[email protected]      yes
NULL                 yes
NULL                 yes

If you are using users_email_unique as your primary key then, as pointed out in the comments, you may need to either:

  • generate a random unique email temporarily for 'fake' users
  • reconsider your primary key for your table (perhaps some form of unique ID?)
  • perhaps split into two tables, one for 'real' users and one for 'fake'

Upvotes: 3

Luca Bruzzone
Luca Bruzzone

Reputation: 561

You can act in 2 ways:

  • delete the line where the email is null (if there are user that aren't fake this process will kill their accounts)
  • give a random email with a custom domain like [email protected] and then you can control in the class when you log in if the mail matches the fake mail and ask to the user to insert a real mail if he want to continue using the website

(eventually you can have the 2nd solution for a while and then pass to the 1st)

Upvotes: 0

Related Questions