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

Laravel foreignId and foreignIdFor Function


2 years ago


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.

Schema::table('posts', function (Blueprint $table) {


After Using foreignIdFor Function

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

Schema::table('posts', function (Blueprint $table) {
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.

Schema::table('posts', function (Blueprint $table) {
Now when you run "php artisan migrate" you will see the foreign key above defined in the table column definition.
notion avatar


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






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