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

11 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.

Snippets by

PostSrc poster

PostSrc

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

new

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

More