Ileana Profeanu
Ileana Profeanu

Reputation: 387

Eloquent Foreign key constraint is incorrectly formed laravel

I am trying to add a foreign key to the 'users' table. These are the time stamps of the migration

eloquent migrations

And this is the code:

Schema::create('types', function (Blueprint $table) {
        $table->increments('id');
        $table->string('types');
        $table->timestamps();
    });

Schema::create('users', function (Blueprint $table) {
        //...
        $table->integer('type')->length(10)->unsigned();
        $table->foreign('type')->references('id')->on('types')->onDelete('cascade');
        $table->rememberToken();
        $table->timestamps();
    });

I really don't know what I do wrong.

EDIT Here is what happens after the suggestions which I received

error message

Upvotes: 1

Views: 982

Answers (1)

dparoli
dparoli

Reputation: 9161

Try to add the foreign key only after you created the table, i.e:

public function up()
{
    Schema::create('users', function (Blueprint $table) {
        //...
        // $table->integer('type')->length(10)->unsigned();
        $table->unsignedInteger('type');       
        $table->rememberToken();
        $table->timestamps();
    });

    Schema::table('users', function (Blueprint $table) {
        $table->foreign('type')->references('id')->on('types')->onDelete('cascade');
    });
}

And probably its better to use $table->unsignedInteger('type');

Update:

The conclusion is that type is a reserverd word in MYSQL.

Upvotes: 3

Related Questions