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

Desssha's avatar

Integrity constraint violation: 1451 Cannot delete or update a parent row: a foreign key constraint fails

excuse me how can delete i try use of of this method but not successful

1- $room_info = Room::where("id", $id)->delete();

2-  DB::table('rooms')->where('id',$id)->delete();

i understand that Rooms have foreign in bookings what best method to delete it with foreign key. thxs

Illuminate\Database\QueryException: SQLSTATE[23000]: Integrity constraint violation: 1451 Cannot delete or update a parent row: a foreign key constraint fails (hotelbooking.bookings, CONSTRAINT bookings_room_id_foreign FOREIGN KEY (room_id) REFERENCES rooms (id)) (SQL: delete from rooms where id = 3) in file

0 likes
5 replies
bugsysha's avatar
bugsysha
Best Answer
Level 61
$room = Room::find($id);
$room->bookings()->delete();
$room->delete();
2 likes
Desssha's avatar

thxs man it worked with me. was trying some method like it but not worked $room=Room::find($id); $room->bookings()->detach(); $room>delete(); but your method work thxs

bugsysha's avatar

You probably have one-to-many relationship and I've never tried detach() for it. So maybe that failed. It is important that it works for you. Thanks. All best.

Desssha's avatar

yes relation was one-to-many because it detach() wasn't work .

Please or to participate in this conversation.