Laravel Tips to Set Foreign Key in Laravel Migration

Hello Artisan

In this quick Laravel tips tutorial i will show you how to set foreign key in laravel migration. I will show you the best way that you can write foreign key in your relationship table. Today I would like to write about a quick tip to use when writing foreign keys in Laravel 7 and Laravel 8. 

This tips will help you write shorter migrations and make your code more readable. For our tutorial, I am going to use the user_id which is very common but this can be applied to any foreign key.

In the past we would write something like this:

$table->unsignedBigInteger('user_id')
->index();

$table->foreign('user_id')
->references('id')
->on('users')
->onDelete('cascade');

 

Look, pretty verbose right?

The good news Dear reader is that we can write this same functionality like this:

$table->foreignId('user_id')
->index()
->constrained()
->onDelete('cascade');

 

I think it is much nicer and easier to read, I hope you enjoyed this tip.