Skip to content
On this page

Foreign Keys in Laravel

Modern Syntax

php
$table->foreignId('user_id')->constrained();
  • Creates unsignedBigInteger('user_id')
  • Adds foreign key to table users on column id (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:

  1. Update the referenced column to bigIncrements, or
  2. 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() like foreignId()

💡 Use foreignId() when your related table uses bigIncrements.
For legacy tables with int primary keys, use foreign() instead.

👉 Laravel Docs