Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

linuxoid's avatar

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?

0 likes
6 replies
SilenceBringer's avatar

@linuxoid you forgot user_id field

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');
    });
}
1 like
SilenceBringer's avatar
Level 55

@linuxoid try

$table->foreignId('user_id')->nullable()->constrained('users')->onDelete('set null');
1 like
georgeOluabisola's avatar

@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');
    });
}

Please or to participate in this conversation.