Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

shahr's avatar
Level 10

Cannot add or update a child row: a foreign key constraint fails

What is this error?

SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (digikala_laravel.types, CONSTRAINT types_color_id_foreign FOREIGN KEY (color_id) REFERENCES colors (id) ON DELETE CASCADE) (SQL: insert into types (warranty_id, color_id, date, time, price, updated_at, created_at) values (2, 0, 1402/01/04, 1679616000, 1000000, 2023-03-24 14:59:23, 2023-03-24 14:59:23))

0 likes
2 replies
LaryAI's avatar
Level 58

This error occurs when you are trying to insert a record into a child table that references a non-existent record in the parent table. In this case, the error is occurring because you are trying to insert a record into the types table with a color_id of 0, which does not exist in the colors table.

To fix this error, you need to make sure that the color_id you are trying to insert into the types table exists in the colors table. You can do this by either inserting the missing color_id into the colors table or by updating the color_id in the types table to reference an existing color_id in the colors table.

Here's an example of how you can update the color_id in the types table to reference an existing color_id in the colors table:

// First, find an existing color_id in the colors table
$color = DB::table('colors')->where('name', 'Red')->first();

// Then, update the color_id in the types table to reference the existing color_id
DB::table('types')->where('id', 1)->update(['color_id' => $color->id]);

In this example, we are finding an existing color_id in the colors table with the name "Red" and then updating the color_id in the types table with an id of 1 to reference the existing color_id.

Please or to participate in this conversation.