Can anybody help me to solve this problem?
There are 3 tables with 2 foreign keys:
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('email')->unique();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
Schema::create('firms', function (Blueprint $table) {
$table->increments('id');
$table->string('title')->nullable();
$table->integer('user_id')->unsigned()->nullable();
$table->foreign('user_id')->references('id')->on('users');
$table->timestamps();
});
Schema::create('jobs', function (Blueprint $table) {
$table->increments('id');
$table->string('title')->nullable();
$table->integer('firm_id')->unsigned()->nullable();
$table->foreign('firm_id')->references('id')->on('firms');
$table->timestamps();
});
Error after running migration:
[Illuminate\Database\QueryException]
SQLSTATE[HY000]: General error: 1005 Can't create table `job`.`#sql-5fc_a1`
(errno: 150 "Foreign key constraint is incorrectly formed") (SQL: alter ta
ble `firms` add constraint `firms_user_id_foreign` foreign key (`user_id`)
references `users` (`id`))
[PDOException]
SQLSTATE[HY000]: General error: 1005 Can't create table `job`.`#sql-5fc_a1`
(errno: 150 "Foreign key constraint is incorrectly formed")
In Laravel 5.8, sometime when you generate a create table migration with a foreign key constraints, running migration may encounter 150 “Foreign key constraint is incorrectly formed” error. This is mainly happens when you take foreign key column of integer type instead of bigInteger, and this new laravel convention was causing this error.
Default migrations in Laravel 6+ use bigIncrements(), so you need to use unsignedBigInteger() method: laravel foreign ke (error: 150 "foreign key constraint is incorrectly formed") (detalles…)
Well this answer is related to Laravel 7.x. So the error: can occur due many reason while migrating the migrations. The one common reason that I am familiar about is order of migration. Lets say we have two table "users" and "roles", and "users" table have a foreign key referring the "id" column on "roles" table.
Am using Laravel 8 and had the same error. The issue is that a both those columns eg users.id and meals.user_id where user_id is the foreign key need to be the same.
In case of foreign keys, the referenced and referencing fields must have exactly the same data type.
You create the id
fields in both users
and firms
as signed integers. However, you create both foreign keys as unsigned integers, therefore the creation of the keys fail.
You need to either add the unsigned
clause to the id
field definitions, or remove the unsigned
clause from the foreign key fields.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With