# Laravel: SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry 'x@example.com' for key 'users_email_unique'

**Code:** `SQLSTATE[23000]: Integrity constraint violation` · **Category:** Laravel · **Seen on:** Laravel, PHP, MySQL

The query violated a database constraint — a duplicate value in a unique column or a missing/blocked foreign key.

## Meaning

1062 = duplicate entry (unique index), 1452 = foreign key parent row missing, 1048 = column cannot be null, 1451 = cannot delete a row referenced elsewhere. Validate with `unique:` rules, use `firstOrCreate`/`upsert`, and check relations before insert/delete.

## Common causes

- Duplicate value in a unique column
- Foreign key points to a non-existent parent (1452)
- Inserting null into a NOT NULL column (1048)
- Deleting a parent that has children (1451)
- Race condition on concurrent inserts

## Quick fix

1. Add validation `unique:users,email` and use `firstOrCreate()` / `upsert()`
2. Create parents first; cascade deletes (`onDelete('cascade')`) if intended
3. Catch `QueryException` and read `errorInfo[1]`

## Detailed fix by platform

### Laravel

1. `User::firstOrCreate(['email' => $email], ['name' => $name]);`

## How to diagnose

1. **Code** — 1062, 1452, 1048, 1451?
2. **Index** — Which key?
3. **Flow** — Concurrent inserts?

---
Source: [WhatIsMyError](https://whatismyerror.com/errors/laravel/sqlstate-23000-integrity-constraint-violation)
