'Migration in Laravel 8, does not let me put foreign key in the default table of users
I have an error when placing a foreign key in the users table of laravel.
I have the Laravel users table, and I want to relate it to the employees table, which will have the personal data of the employees, but when I try to put the foreign key inside the users table, I get an error:
PDOException::("SQLSTATE[HY000]: General error: 1005 Can't create table name_data_base.users (errno: 150 "Foreign key constraint is incorrectly formed")")
This error only occurs in this relationship, since I have more tables and it does not give me a problem.
This is the code for the two tables:
employees table
public function up()
{
Schema::create('employees', function (Blueprint $table) {
$table->id();
$table->foreignId('person_id')->references('id')->on('people');
$table->timestamps();
});
}
users table
public function up()
{
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->rememberToken();
$table->timestamps();
$table->foreignId('employee_id')->references('id')->on('employees');
});
}
Solution 1:[1]
You need to defined column employee_id in employees table migration file Schema:
Remember employee_id column type, length or unsigned like properties should be same users table primary key id. Here is docs help:Foreign Key Constraints
Schema::create('employees', function (Blueprint $table) {
$table->id();
$table->foreignId('person_id')->references('id')->on('people');
//By default laravel create primary key with bigInteger in latest versions
$table->bigInteger('employee_id')->unsigned();
$table->timestamps();
$table->foreign('employee_id')->references('id')->on('users');
});
Now run php artisan migrate so it will create table employees and foreign key too.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Faizan Ali |
