Back to Error Center

Unique constraint violation

Error Message

SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry for key

Cause

Trying to insert a record with a value that violates a UNIQUE constraint. The value already exists in the unique column.

Solution

Check for existing records before inserting. Use firstOrCreate() or updateOrCreate() for upsert operations. Validate uniqueness in Form Requests.

Code Example

Fix
// Use firstOrCreate to avoid duplicates
$user = User::firstOrCreate(
    ['email' => $email],
    ['name' => $name, 'password' => $password]
);

// Validate uniqueness in Form Request
public function rules(): array
{
    return [
        'email' => ['required', 'email', 'unique:users,email'],
    ];
}

// On update, ignore the current record
'email' => ['required', 'email', Rule::unique('users')->ignore($user->id)],

Debugging Steps

  1. Check which column has the unique constraint
  2. Verify if a record with that value already exists
  3. Check the unique index name in the error message
  4. Review the migration for unique constraints

Prevention

Always validate uniqueness in Form Requests. Use firstOrCreate for idempotent operations. Add unique constraints in migrations.