Skip to content
Advertisement

SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row in Laravel9

I have an integrity constraint violation when I run the php artisan db:seed command in Laravel 9.

Error

PDOException::(“SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (hunger-db.restaurants, CONSTRAINT restaurants_user_id_foreign FOREIGN KEY (user_id) REFERENCES users (id) ON DELETE CASCADE)”)

setup_users_table

JavaScript

setum_restaurants_table

JavaScript

User Model

JavaScript

Restaurant Model

JavaScript

Advertisement

Answer

I see some things to change here

setup_restaurants_table

I don’t see with good eyes user_id with default 1, maybe is better to define the value when restaurant is created or manually assign it to user 1.

JavaScript

After DB changes run php artisan migrate:fresh

User.php

Should change relation to hasMany Restaurants

JavaScript

Seeding

Also ensure your DB seeding is correct, I mean creating user first and then restaurant, set user_id with an existing value.

Maybe creating a restaurant like this:

JavaScript

If any factory change run php artisan db:seed

Can also see Factory Retationship Docs

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement