Duplicate Entry
The code tries to insert a record with a value that already exists in a unique column.
Explanation
Duplicate entry is a database error that occurs when you try to insert or update a record with a value that violates a UNIQUE constraint or PRIMARY KEY constraint. This means the value already exists in the table for that column. Common causes include attempting to register with an existing email, inserting duplicate records without checking, race conditions in concurrent requests, or missing uniqueness validation. The error typically includes the specific key that caused the violation.
Common Causes
- Unique constraint violation
- Duplicate primary key insertion
- Race condition in concurrent requests
- Missing uniqueness validation
- Bulk insert with duplicates
Solution
Use database-level unique constraints and handle the exception gracefully. In Laravel, use firstOrCreate() or updateOrCreate() for idempotent operations. Add unique validation rules: 'email' => 'unique:users,email'. Use database transactions with proper error handling. For bulk inserts, use INSERT IGNORE or ON DUPLICATE KEY UPDATE. Check for existing records before inserting. Handle the QueryException for duplicate entries (MySQL error code 1062) with appropriate user feedback.
Code Example
// This fails if email already exists
User::create(['email' => 'existing@example.com', 'name' => 'John']);
// QueryException: Duplicate entry 'existing@example.com' for key 'users_email_unique'
// Fix: use firstOrCreate for idempotent operations
$user = User::firstOrCreate(
['email' => 'existing@example.com'], // search criteria
['name' => 'John'] // create if not found
);
// Validation rule
$request->validate([
'email' => 'required|email|unique:users,email',
]);
// Handle duplicate entry exception
try {
User::create($data);
} catch (QueryException $e) {
if ($e->errorInfo[1] == 1062) {
return back()->withErrors(['email' => 'Email already registered']);
}
throw $e;
}
// On Duplicate Key Update (MySQL)
DB::statement('INSERT INTO users (email, name) VALUES (?, ?)
ON DUPLICATE KEY UPDATE name = VALUES(name)',
['email' => 'test@example.com', 'name' => 'Updated']);
Error Information
Language
php
Framework
laravel
Difficulty
Beginner
Views
457
Related Errors
Database
TypeORM/SQLAlchemy EntityNotFoundError
The ORM cannot find the requested entity or model in the database.
Database
Lock Wait Timeout Exceeded
A database query waited too long for a lock held by another transaction.
429
Backend
Rate Limit Exceeded (429)
Too many requests were sent in a given amount of time.
Database
Unknown Column
The SQL query references a column that doesn't exist in the specified table.