Laravel 7+ Foreign Keys

From Laravel 7, in migrations you don't need to write two lines for relationship field - one for the field and one for foreign key. Use method foreignId().

1// Before Laravel 7
2Schema::table('posts', function (Blueprint $table)) {
3 $table->unsignedBigInteger('user_id');
4 $table->foreign('user_id')->references('id')->on('users');
5}
6 
7// From Laravel 7
8Schema::table('posts', function (Blueprint $table)) {
9 $table->foreignId('user_id')->constrained();
10}
11 
12// Or, if your field is different from the table reference
13Schema::table('posts', function (Blueprint $table)) {
14 $table->foreignId('created_by_id')->constrained('users', 'column');
15}

Like our articles?

Become a Premium Member for $129/year or $29/month
What else you will get:
  • 22 courses (477 lessons, total 38 h 20 min)
  • 2 long-form tutorials (one new every week)
  • access to project repositories
  • access to private Discord