Search code examples
phpmysqllaraveldatabaselaravel-9

Laravel 9 adding foreign key constraint returns 150 error


I have created Roles table with Users table, I am trying to add foreign key to users table, but when I migrate, it returns 150 error.
enter image description here
I have googled a lot, I got a lot of answers, but no answer worked for me.
create_users_table Migration:

Schema::create('users', function (Blueprint $table) {
    $table->id();
    $table->string('name');
    $table->string('email')->unique();
    $table->timestamp('email_verified_at')->nullable();
    $table->string('password');
    $table->foreignId('role_id')
            ->constrained()
            ->onUpdate('cascade')
            ->onDelete('cascade');
    $table->rememberToken();
    $table->timestamps();
});

create_roles_table Migration:

Schema::create('roles', function (Blueprint $table) {
    $table->id();
    $table->string('name');
    $table->timestamps();
});

Can someone tell me what's wrong? I am stuck..


Solution

  • The problem is that roles table doesn't exist when you're creating a foreign key inside the users table.

    So, your roles migration must be executed before you create a foreign key inside the users table.

    There are 2 ways you can do this.

    1- You either rename the roles and change the timestamp in name to be before the users migration. ( Not a good way though )

    2- First create the tables and then create a new migration to insert the foreign key inside the users table.