When defining a database relationship, you can use the foreignId()
or foreignIdFor()
methods to add a foreign key. Let's take a look at the examples.
Syntax 1. ForeignId()
One of the most common ways to define a relationship is foreignId()
:
Migration
Schema::create('posts', function (Blueprint $table) { $table->id(); $table->foreignId('user_id')->constrained();});
The method constrained()
will tie both tables together with Database Validation and won't allow you to delete a user if it has any posts.
Syntax 2. UnsignedBigInteger() with foreign()
Before Laravel 7, there was no foreignId()
method, and you needed to manually create a field and a foreign key. That syntax still works if you prefer it.
It will create a new column user_id
of type unsignedBigInteger
.
Schema::create('posts', function (Blueprint $table) { $table->id(); $table->unsignedBigInteger('user_id'); $table->foreign('user_id')->references('id')->on('users');});
Syntax 3. ForeignIdFor()
Laravel also has a foreignIdFor()
method, which will set the column name from the model:
Migration
Schema::create('posts', function (Blueprint $table) { $table->id(); $table->foreignIdFor(User::class)->constrained();});
It will create a new column user_id
of type unsignedBigInteger
.
Extra. Constrained() with Non-Standard Tables/Fields
If you have a table name that doesn't match the column name, you can pass the table name as the second parameter.
For example, if your table name is called users
but the column is called author_id
instead of user_id
, you can specify the related table or Model:
Migration
Schema::create('posts', function (Blueprint $table) { $table->id(); $table->foreignId('author_id')->constrained('users'); // Or $table->foreignIdFor(User::class, 'author_id');});
Similarly, if the primary key of that related table isn't called id
, you can specify its value, too, after the table name.
Example with uuid
instead of id
:
Migration
Schema::create('posts', function (Blueprint $table) { $table->id(); $table->foreignId('author_id')->constrained('users', 'uuid'); // Or $table->foreignIdFor(User::class, 'author_id')->constrained('users', 'uuid');});
I always use Syntax 2 and it's comfortable.
I always use syntax 1, but syntax 3 is interesting, I didn't know.