Posted: 01-08-2020

Add Foreign Key References in Laravel 7 Migration

Add Foreign Key References in Laravel  7 Migration

Creating Foreign Key References in Laravel Migration is one of the my tedious and confusing task.

In order to create a foreign Key references it's important that the column the constraint refers to must e of the same type and width as the foreign column

the counter_id must be a bigInt(20) as the reference id create using the  $table->id() method

For example

Schema::create('counters', function (Blueprint $table) {
$table->id();
$table->string('title', 255);
$table->integer('sort')->nullable();
$table->boolean('pub')->nullable()->default(1);
$table->timestamps();
});

and  then

Schema::create('counter_translations', function (Blueprint $table) {
$table->id();
$table->bigInteger('counter_id')->unsigned();
.......
$table->foreign('counter_id')->references('id')->on('counters')->onDelete('cascade');
});