virtual
virtual

Reputation: 3

Laravel migration can not add foreign key in user table

I want to add a foreign key in the users table. Everything seems ok yet I get the following error.

SQLSTATE[HY000]: General error: 1005 Can't create table electro_service.#sql-17d0_20 (err no: 150 "Foreign key constraint is incorrectly formed") (SQL: alter table users add constraint users_role_id_foreign foreign key ( role_id) references roles (id) on delete cascade).

Users

public function up()
{
    Schema::create('users', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->unsignedBigInteger('role_id');
        $table->foreign('role_id')->references('id')->on('roles')->onDelete('cascade');
        $table->string('name');
        $table->string('mobile');
        $table->string('code');
        $table->string('email')->unique();
        $table->tinyInteger('email_verified')->default(0);
        $table->string('email_verification_token', 128)->nullable();
        $table->string('image')->default('default.png');
        $table->timestamp('email_verified_at')->nullable();
        $table->string('password');
        $table->rememberToken();
        $table->timestamps();
    });
}

Roles

public function up()
{
    Schema::create('roles', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->string('name');
        $table->tinyInteger('role')->default(0);
        $table->string('slug')->unique();
        $table->timestamps();
    });
}

Please tell me how can I fix it and where changes will be needed.

Upvotes: 0

Views: 959

Answers (1)

manu
manu

Reputation: 351

Rename user migration file date to greater, than roles

example :

2019_06_06_135936_create_roles_table
2019_06_06_135937_create_users_table

Now the roles table will get created before users migration

Upvotes: 2

Related Questions