Search code examples
phpmysqllaravellaravel-5database-migration

Adding a foreign key constraint with a Laravel Migration


I have started a new Laravel 5.5 project and I am receiving the following error when trying to add a foreign key to my users table:

General error: 1215 Cannot add foreign key constraint (SQL: alter table users add constraint users_organization_id_foreign foreign key (organization_id) references organizations (id) on delete cascade)

Here is the migration code for the organization table:

Schema::create('organizations', function (Blueprint $table) {
    $table->increments('id');
    $table->string('name');
    $table->string('subdomain')->nullable();
    $table->timestamps();
    $table->softDeletes();
});

Here is the migration code for the users table:

Schema::create('users', function (Blueprint $table) {
    $table->increments('id');
    $table->integer('organization_id')->unsigned();
    $table->foreign('organization_id')->references('id')->on('organizations');
    $table->string('first_name');
    $table->string('last_name');
    $table->string('email')->unique();
    $table->timestamps();
    $table->softDeletes();
});

I have researched this error online and the common thing to make sure of are that the data types are the same. From what I can see, they are the same. What's even crazier is that if I run this query in the database directly it works:

alter table `users` add constraint `users_organization_id_foreign` foreign key (`organization_id`) references `organizations` (`id`)

Solution

  • By default, in each Laravel fresh installation users table is created first. But since you're adding a constraint in this table, you need to create organizations table first.

    So, put organizations table migration before users table migration by changing organizations migration date in the file name:

    2014_01_01_000000_create_organizations_table.php