Laravel 8: Foreign key constraint is incorrectly formed
Migration:
public function up()
{
Schema::create('posts', function (Blueprint $table) {
$table->id();
$table->string('uid')->unique();
$table->string('title');
$table->text('description');
$table->text('content');
$table->boolean('active')->default(true);
$table->timestamps();
$table->foreignId('user_id')->constrained('users')->onDelete('set null');
});
}
throws:
SQLSTATE[HY000]: General error: 1005 Can't create table `laravel`.`posts` (errno: 150 "Foreign key constraint is incorrectly formed") (SQL: alter table `posts` add constraint `posts_user_id_foreign` foreign key (`user_id`) references `users` (`id`) on delete set null)
while the posts migration file name date time 2021_05_25_012345_create_posts_table is later than the user's 2014_10_12_000000_create_users_table. Why's that happen?
public function up()
{
Schema::create('posts', function (Blueprint $table) {
$table->id();
$table->unsignedBigInteger('user_id'); // this one
$table->string('uid')->unique();
$table->string('title');
$table->text('description');
$table->text('content');
$table->boolean('active')->default(true);
$table->timestamps();
$table->foreignId('user_id')->constrained('users')->onDelete('set null');
});
}
The docs say "The example above can be rewritten like so", i.e. your example is equivalent to mine. I read it as the '$table->unsignedBigInteger('user_id');' can be replaced by '$table->foreignId('user_id')'
@linuxoid you forgot to add the user_id field and attach the nullable() method to the user_id field.
public function up()
{
Schema::create('posts', function (Blueprint $table) {
$table->id();
$table->unsignedBigInteger('user_id')->nullable(); // note this line
$table->string('uid')->unique();
$table->string('title');
$table->text('description');
$table->text('content');
$table->boolean('active')->default(true);
$table->timestamps();
$table->foreignId('user_id')->constrained('users')->onDelete('set null');
});
}