Home > Net >  Error adding foreign key in migration [Laravel 8] (errno: 150 "Foreign key constraint is incorr
Error adding foreign key in migration [Laravel 8] (errno: 150 "Foreign key constraint is incorr

Time:10-09

I have my users

Schema::create('users', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('email')->unique();
            $table->enum('role', ['admin', 'operator', 'owner']);
            $table->string('password');
            $table->foreignId('profile_id')->constrained('profile');
            $table->rememberToken();
            $table->timestamps();
        });

I have my profile

Schema::create('profile', function (Blueprint $table) {
            $table->id();
            $table->string('full_name');
            $table->bigInteger('phone');
            $table->string('address');
            $table->enum('gender', ['men', 'women']);
        });

Everytime I tried to migrate it popped up error

SQLSTATE[HY000]: General error: 1005 Can't create table `myDatabase`.`users` (errno: 150 "Foreign key constraint is incorrectly formed") (SQL: alter table `users` add constraint `users_profile_id_foreign` foreign key (`profile_id`) references `profile` (`id`))

I heard and know this error can happen if the both data type is not the same, since I have encounter this problem before and manage to fix it by making sure both data type is the same. But I think the data type is already the same right? Am I missing something? Or the problem is not the data type? Thanks!

CodePudding user response:

The known cause of this problem would the sequence, If your "Users" migration file is running before "Profile" Migration file, then this scenario can happen.

The solution would be is to change the migration filename so that "Profile" migration file runs first.

  • Related