Search code examples
migrationlaravel-9

Can't create foreign key on another table using ID of my users table [Foreign key constraint is incorrectly formed]


I was trying to create a comments table that was going to have a foreign key user_id that refferenced the "ID" on users table. But each time I ran my migration, I kept getting this error.

SQLSTATE[HY000]: General error: 1005 Can't create table 9anime.comments (errno: 150 "Foreign key constraint is incorrectly formed") (SQL: alter table comments add constraint comments user_id foreign foreign key (user_id) references users (id) on delete cascade)

My users migration code

 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();
        });

My comments migration file

 Schema::table('comments', function (Blueprint $table) {
            $table->unsignedInteger('user_id');
            $table->foreign('user_id')->references('id')->on('users')->cascadeOnDelete();
        });

When I run my migration, I get that error. I looked at my code and did not find anything wrong with it. This answer suggested that the user_id be made nullable. I did that but it did not change anything


Solution

  • I edited the users migration file, specifically this line

    $table->id();

    to

    $table->increments('id');

    then ran my migration and it worked