Home / Snippets / Laravel foreignId and foreignIdFor Function
Laravel foreignId and foreignIdFor Function cover

Laravel foreignId and foreignIdFor Function

7.7K

3 years ago

0 comments

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.
notion avatar

Alaz

Week-end developer currently experimenting with web, mobile, and all things programming.

Topics:

Frontend

Resource

Average

Average

Support Us

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

Welcome to PostSrc V3

PostSrc Dark Logo

You have to login to favorite this