Appearance
Foreign Keys in Laravel
Modern Syntax
php
$table->foreignId('user_id')->constrained();
- Creates
unsignedBigInteger('user_id') - Adds foreign key to table
userson columnid(name conventions).
With cascade:
php
$table->foreignId('user_id')
->constrained()
->cascadeOnUpdate(); // or $table->restrictOnUpdate();
->cascadeOnDelete(); // or ->nullOnDelete() / ->restrictOnDelete()
Custom table/index:
php
$table->foreignId('user_id')
->constrained('posts_user_id', 'users');
If you want to make the foreign key nullable, this has to be declared before the constrained method.
php
$table->foreignId('user_id')
->nullable() // Make sure to call this before constrained https://github.com/laravel/framework/issues/32460
->constrained()
->cascadeOnUpdate(); // or $table->restrictOnUpdate();
->cascadeOnDelete(); // or ->nullOnDelete() / ->restrictOnDelete()
Legacy Setup (for integer IDs)
In older Laravel apps, $table->id() created an unsigned integer instead of bigInteger.
Because foreignId() always creates an unsignedBigInteger, it will not match in this case, and cause foreign key errors.
You must either:
- Update the referenced column to
bigIncrements, or - Define the foreing key manually like this:
php
$table->integer('user_id')->unsigned();
$table->foreign('user_id')
->references('id') // constrained() does not work for foreign()
->on('users')
->cascadeOnUpdate(); // or $table->restrictOnUpdate();
->cascadeOnDelete(); // or ->nullOnDelete() / ->restrictOnDelete()
foreignId() vs foreign()
foreignId()
- Returns
Illuminate\Support\Fluent - Supports
->constrained() - Also supports
->references()and->on() - Creates the column and foreign key in one step
foreign()
- Returns
Illuminate\Database\Schema\ForeignKeyDefinition - Does not support
->constrained() - Requires existing column
- Supports
->references()and->on()likeforeignId()
💡 Use
foreignId()when your related table usesbigIncrements.
For legacy tables withintprimary keys, useforeign()instead.
👉 Laravel Docs