Umut Savas
Umut Savas

Reputation: 113

Laravel throws General error: 1215 Cannot add foreign key constraint" when I create foreign keys

I am using Laravel 6. I created a few migrations but I can't let them run successfully. These are my migrations.

    public function up()
{
    Schema::create('nationalities', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->string('name');
        $table->timestamps();
        $table->engine = "InnoDB";
    });


    public function up()
{
    Schema::create('genders', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->string('name');
        $table->timestamps();
        $table->engine = "InnoDB";
    });


    public function up()
{
    Schema::create('users', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->string('firstname');
        $table->string('lastname');
        $table->string('street');
        $table->string('zip');
        $table->string('city');
        $table->date('birthdate');
        $table->string('gender');
        $table->string('email')->unique();
        $table->timestamp('email_verified_at')->nullable();
        $table->string('password');
        $table->rememberToken();
        $table->timestamps();
        $table->unsignedBigInteger('gender_id');
        $table->unsignedBigInteger('nationality_id');
        $table->engine = "InnoDB";
        $table->foreign('gender_id')->references('id')->on('gender');
        $table->foreign('nationality_id')->references('id')->on('nationality');
    });
}

After executing php artisan migrate I get this error message:

General error: 1215 Cannot add foreign key constraint (SQL: alter table users add constraint users_gender_id_foreign foreign key (gender_id) references gender (id))

What am I doing wrong?

Upvotes: 0

Views: 31

Answers (1)

lagbox
lagbox

Reputation: 50541

Your table name is genders not gender and nationalities not nationality:

Change:

...->references('id')->on('gender');
...->references('id')->on('nationality');

To:

...->references('id')->on('genders');
...->references('id')->on('nationalities');

Upvotes: 1

Related Questions