Laravel - Migrations - Foreign Key Constraints
Laravel also provides support for creating foreign key constraints, which are used to force referential integrity at the database level. For example, let's define a user_id
column on the posts
table that references the id
column on a users
table:
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
Schema::table('posts', function (Blueprint $table) {
$table->unsignedBigInteger('user_id');
$table->foreign('user_id')->references('id')->on('users');
});
Since this syntax is rather verbose, Laravel provides additional, terser methods that use conventions to provide a better developer experience. When using the foreignId
method to create your column, the example above can be rewritten like so:
Schema::table('posts', function (Blueprint $table) {
$table->foreignId('user_id')->constrained();
});
The foreignId
method creates an UNSIGNED BIGINT
equivalent column, while the constrained
method will use conventions to determine the table and column name being referenced. If your table name does not match Laravel's conventions, you may specify the table name by passing it as an argument to the constrained
method:
Schema::table('posts', function (Blueprint $table) {
$table->foreignId('user_id')->constrained('users');
});
You may also specify the desired action for the "on delete" and "on update" properties of the constraint:
$table->foreignId('user_id')
->constrained()
->onUpdate('cascade')
->onDelete('cascade');
An alternative, expressive syntax is also provided for these actions:
Any additional column modifiers must be called before the constrained
method:
$table->foreignId('user_id')
->nullable()
->constrained();