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

In my migration file , I am adding organization id to the user’s table , i tried all of the code below but not solved yet

class AddOrganizationIdToUsersTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('users', function (Blueprint $table) {
//            $table->foreignId('organization_id')->references('id')->on('organizations')->onDelete('cascade');
            $table->foreignId('organization_id')->constrained('organizations')->cascadeOnDelete();
//            $table->foreign('organization_id')->references('id')->on('organizations')->onDelete('cascade');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('users', function (Blueprint $table) {
            //
        });
    }

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

I have data on my user’s table so it is giving errors while migrating, to solve it I add the field as nullable

$table->foreignId('organization_id')->nullable()->references('id')->on('organizations')->onDelete('cascade');

Method 2

if you write with foreignId need:

$table->foreignId('organization_id')->constrained('organizations')->cascadeOnDelete();

or just foreign
$table->foreign('organization_id')->references('id')->on('organizations')->onDelete('cascade');

Method 3

What could be the issue is that this migration is running before the organizations table migration, and when it tries to find it to create the constraint it fails.

What I would suggest is on the AddOrganizationIdToUsersTable :

Schema::table('users', function (Blueprint $table) {
            $table->foreignId('organization_id');
        });

And on the Organization creation migration:
Schema::table('users', function(Blueprint $table) {
            $table->foreign('organization_id')->references('id')->on('organizations');
        });

#2 solution:
Move the migration of Organization table to run before your AddOrganizationIdToUsersTable by changing the timestamp on the name of the file


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x