You want a foreign key to become null when the parent row is deleted, instead of the delete failing or removing the child.
The migration
Schema::create('pictures', function (Blueprint $table) {
$table->id();
$table->string('path');
});
Schema::create('galleries', function (Blueprint $table) {
$table->id();
$table->string('title');
$table->foreignId('picture_id')->nullable()->constrained('pictures')->nullOnDelete();
});
Schema::create('photos', function (Blueprint $table) {
$table->id();
$table->string('path');
$table->foreignId('gallery_id')->constrained('galleries')->cascadeOnDelete();
});
nullOnDelete()setspicture_idtonullwhen the picture is deleted. The gallery stays.cascadeOnDelete()deletes the photos when their gallery is deleted.- The column has to be
nullable()for set null to work. - Create the parent table first, because a foreign key can only point at a table that exists.
The older spelling does the same thing:
$table->unsignedBigInteger('picture_id')->nullable();
$table->foreign('picture_id')->references('id')->on('pictures')->onDelete('set null');
SQLite
SQLite only enforces foreign keys when PRAGMA foreign_keys is on. Laravel turns it on for SQLite connections by default (foreign_key_constraints in config/database.php), so these rules work in tests too. If a delete does not null the column, check that option.
The constraint is enforced by the database. Deleting through query builder or Eloquent both trigger it. Model events for the children do not fire.
Tested on Laravel 10.x (PHP 8.1) and 12.x (PHP 8.3) with SQLite in memory: the tests delete a picture and check the gallery remains with a null column, delete a gallery and check its photos go, and check that the pragma is on. Source: tests/laravel-verification/files/q604.