Posted: 26-12-2020

Laravel 8 Add Foreign Key References

Laravel 8 Add Foreign Key References

Laravel 8 provides support for creating foreign key constraints, which are used to force referential integrity at the database level.

You can use the conventional sintax like this:

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

Schema::table('faq_translations', function (Blueprint $table) {
    $table->unsignedBigInteger('faq_id');
    $table->foreign('faq_id')->references('id')->on('faqs');
});


But Laravel also provides additional, terser methods that use conventions to provide a better developer experience.
The example above can be rewritten in shorthand:

Schema::table('faqs', function (Blueprint $table) {
    $table->foreignId('faq_id')->constrained(); 
});


In addition may also specify the desired action for the "on delete" and "on update" properties of the constraint:

Schema::table('faqs', function (Blueprint $table) {
    $table->foreignId('faq_id')
->constrained()

->onUpdate('cascade') ->onDelete('cascade');
});