Back to Error Center

Foreign key constraint fails

Error Message

SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails

Cause

Trying to insert or update a record with a foreign key value that doesn't exist in the referenced table.

Solution

Ensure the referenced record exists before creating the child record. Use constrained() in migrations to enforce referential integrity. Check the foreign key value.

Code Example

Fix
// Ensure parent exists before creating child
$user = User::find($userId);
if ($user) {
    $post = $user->posts()->create([
        'title' => 'My Post',
        'body' => 'Content',
    ]);
}

// In migration - foreign key constraint
Schema::create('posts', function (Blueprint $table) {
    $table->foreignId('user_id')->constrained();
});

Debugging Steps

  1. Verify the foreign key value exists in the parent table
  2. Check the foreign key column name
  3. Verify the parent table has the referenced record
  4. Check for typos in the foreign key value

Prevention

Always verify parent records exist before creating children. Use database transactions for multi-table operations. Use constrained() in migrations.