Posts Learn Components Snippets Categories Tags 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


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.

Snippets by

PostSrc poster


Full stack developer mainly focusing on the front end side of the web. The main author of PostSrc and loves writing tutorial and guides online.

Load comments for Laravel foreignId and foreignIdFor Function


PostSrc Code Components

Collection of Tailwind CSS components for everyone to use. Browse all of the components that's right for your project.

View Components

Other Code Snippets