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

If you are getting error Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails while using php artisan migrate command after creating a migration file. You can set foreign id column value as nullable with null on delete on delete parent table record.

Answers 1
  • Create foreign key as nullable and assign null value on delete record using nullOnDelete method

    --PATH database\migrations\<yourmigrationfile>.php
    $table->unsignedBigInteger('user_id')->nullable();
    $table->foreign('user_id')->references('id')->on('users')->nullOnDelete();
    
    0

    On delete record from the user's table, it will set the column value as null for the column user_id in this table for this specific user. Like if you want to delete the user with id 1 this code snippet will set value null where the foreign key user_id = 1 in this particular table.

    This code snippet with the foreign id column is helpful when you have already existing records in the child table and you want to set it as nullable.

  • Back to code snippet queries related laravel

Related queries helps you to understand and may also used for implementation of current code snippet