I have these migrations in a Laravel 5.8 project, in one I create the Users table and in the other user_profiles , in the second I put a Foreign Key from the "user_id" field to the "id" field of the "users" table
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->rememberToken();
$table->timestamps();
});
}
public function up()
{
Schema::create('user_profiles', function (Blueprint $table) {
$table->increments('id')->unsigned();
$table->integer('user_id')->unique();
$table->integer('age')->nullable();
$table->foreign('user_id')->references('id')->on('users');
});
}
The error obtained is the following
Migrating: 2015_10_12_000000_create_user_profiles_table
Illuminate\Database\QueryException : SQLSTATE[HY000]: General error: 1005 Can't create table
portal
.#sql-4cc8_70
(errno: 150 "Foreign key constraint is incorrectly formed") (SQL: alter tableuser_pro files
add constraintuser_profiles_user_id_foreign
foreign key (user_id
) referencesusers
(id
))
Foreign keys must not contain negative values, which is why you get the error you have there.
Solution: You must add
unsigned()
to your foreign key.I'm not sure it
unique
has to be there, but you can do the following if you really want to:According to the Laravel documentation the declaration of your foreign key must be of this type
And then indicate the link with the primary key in this way
Just as an extra point, since Laravel 5.8 the default data type assigned to a migration in the primary key is of type
bigIncrements()
.So just check this point when creating the migrations and create the relationships between them