Onyx
Onyx

Reputation: 5762

Getting an error when trying to add foreign key constraint using Laravel migrations

I'm trying to figure out foreign keys but when trying to migrate after adding: $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade'); to my code, I get this error:

"SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint (SQL
  : alter table `images` add constraint `images_user_id_foreign` foreign key
  (`user_id`) references `users` (`id`) on delete cascade)
"

Users migration:

Schema::create('users', function (Blueprint $table) {
                $table->increments('id');
                $table->string('first_name');
                $table->string('last_name');
                $table->string('username');
                $table->string('password');
                $table->string('email');
                $table->string('profile_picture')->nullable()->default('image');
                $table->timestamps();
                $table->rememberToken();
                $table->engine = 'InnoDB';
            });

Images migration:

Schema::create('images', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->string('description')->nullable()->default(null);
            $table->integer('user_id');
            $table->foreign('user_id')
                  ->references('id')
                  ->on('users')
                  ->onDelete('cascade');
            $table->string('file_name');
            $table->string('upvotes')->default(0);
            $table->string('downvotes')->default(0);
            $table->string('views')->default(0);
            $table->timestamps();
            $table->engine = 'InnoDB';
        });

Upvotes: 0

Views: 31

Answers (1)

BILAL MALIK
BILAL MALIK

Reputation: 141

That is probably because you're using different datatype, try making the datatype same and it should work. Int - bigInt or string Int , please check.

Also Add it in two steps, and it's good to make it unsigned too.

otherwise it must be some typing mistake.

Upvotes: 1

Related Questions