DEV Community

Cover image for 3 Syntax Ways to Define a BelongsTo Relationship Foreign Key in Laravel Migrations.
Kepson Diaz
Kepson Diaz

Posted on

3 Syntax Ways to Define a BelongsTo Relationship Foreign Key in Laravel Migrations.

In this article we will discover 3 syntax ways to define a belongto relationship foreign key in laravel migrations.

We have two tables Users and Posts, we gonna make a relation between them. User can create many Posts and Post can be create by on User.

1 - First syntax

<?php

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

return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::create('posts', function (Blueprint $table) {
            $table->id();
            $table->unsignedBigInteger('user_id');
            $table->foreign('user_id')->references('id')->on('users');
            $table->timestamps();
        });
    }
};
Enter fullscreen mode Exit fullscreen mode

2 - Second Syntax

<?php

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

return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::create('posts', function (Blueprint $table) {
            $table->id();
            $table->foreignId('user_id')->constrained();
            $table->timestamps();
        });
    }

};
Enter fullscreen mode Exit fullscreen mode

3 - Third syntax

<?php

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

return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::create('posts', function (Blueprint $table) {
            $table->id();
            $table->foreignIdFor(\App\Models\User::class)->constrained();
            $table->timestamps();
        });
    }

};
Enter fullscreen mode Exit fullscreen mode

This 3 syntaxe do the same work. The second syntaxe is the most widely used by laravel developers, but the frist syntaxe can offer more flexibility for example if you want to change the name of the foreign key . The third syntaxe for his case is less verbose.

Is the end of this article. If you have any suggestions for improving this article, please let us know in the comments.

Top comments (0)