Posts Learn Components Snippets Categories Tags Tools new About
/

Laravel foreignId and foreignIdFor Function

Get to know Larave foreignId and foreignIdFor function to simplify your migration code definition

Created on Sep 15, 2021

1960 views

In Laravel, there are foreignId and foreignIdFor functions that can be used to define a foreign key in a migration file. Imagine having a "post" model that has a relation with "user" model. The relationship will be "post" belong to the "user".

Before Using foreignIdFor Function


Before having the foreignIdFor function, the code to define a foreign key is quite long and prote for error.
<?php

Schema::table('posts', function (Blueprint $table) {
    $table->unsignedBigInteger('user_id');

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

After Using foreignIdFor Function


Now you can update the code above with the use of "foreignId" function.
<?php

Schema::table('posts', function (Blueprint $table) {
    $table->foreignId('user_id')->constrained();
});
If you are not sure with the key "user_id" or any other keys that may be internally used by Laravel then you can make use of the "foreignIdFor" function and pass in the Eloquent class like below.
<?php

Schema::table('posts', function (Blueprint $table) {
    $table->foreignIdFor(User::class)->constrained();
});
Now when you run "php artisan migrate" you will see the foreign key above defined in the table column definition.

If you like our tutorial, do make sure to support us by being our Patreon or buy us some coffee ☕️

Load comments for Laravel foreignId and foreignIdFor Function

)