Laravel: delete a record only if no relationship exists

Laravel Questions editorial team
Editorial team · 18 October 2026

To delete a record only when nothing references it, combine two layers: a foreign key with restrictOnDelete() so the database itself refuses to remove a referenced parent, and an application-level exists() check inside a transaction so your app can return a friendly error. The examples use a Telco parent with Operator and Package children on Laravel 11, 12 and 13, MySQL 8 and PHP 8.2 or later.

Get the foreign key direction right first

The foreign key lives on the child table and points at the parent. operators.telco_id references telcos.id, not the other way round:

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    public function up(): void
    {
        Schema::table('operators', function (Blueprint $table) {
            $table->foreignId('telco_id')
                ->constrained('telcos')
                ->restrictOnDelete();
        });
    }
};

The onDelete behaviour decides what happens to a parent that still has children:

  • restrictOnDelete() (or noActionOnDelete()): the database refuses to delete the parent. This is what “delete only if no relationship exists” means at the database level.
  • cascadeOnDelete(): the database deletes the children together with the parent. That is the opposite requirement: it removes dependent records instead of protecting the parent.

Defining foreignId('operator_id') on the telcos table would model a telco belonging to one operator, which inverts the relationship and makes the cascade behave backwards.

Application-level check, inside a transaction

The database constraint is the guarantee; the exists() check is how you turn it into a controlled response instead of an exception:

<?php

namespace App\Services;

use App\Models\Telco;
use Illuminate\Support\Facades\DB;
use RuntimeException;

class TelcoService
{
    public function deleteIfUnreferenced(int $telcoId): bool
    {
        return DB::transaction(function () use ($telcoId) {
            $telco = Telco::query()->lockForUpdate()->findOrFail($telcoId);

            $hasReferences = $telco->operators()->exists()
                || $telco->packages()->exists();

            if ($hasReferences) {
                throw new RuntimeException(
                    "Telco {$telco->id} cannot be deleted: related records exist."
                );
            }

            return (bool) $telco->delete();
        });
    }
}

With the relations defined on the model:

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;

class Telco extends Model
{
    public function operators(): HasMany
    {
        return $this->hasMany(Operator::class);
    }

    public function packages(): HasMany
    {
        return $this->hasMany(Package::class);
    }
}

lockForUpdate() plus the transaction closes most of the race where a child row is inserted between your check and the delete. For the remaining race (a concurrent insert after your transaction commits), the restrictOnDelete() foreign key is the backstop: catch the resulting Illuminate\Database\QueryException (SQLSTATE 23000) and report it as “related records exist”.

This is not soft deletion

An exists() check before deleting has nothing to do with soft deletes. Soft deletion is a separate feature: add the Illuminate\Database\Eloquent\SoftDeletes trait and a deleted_at timestamp column, and delete() then only stamps the row instead of removing it.

The two interact in one important way: if the children use soft deletes, decide whether trashed children should block deletion. By default operators()->exists() ignores soft-deleted rows; use $telco->operators()->withTrashed()->exists() when a trashed child should still protect the parent.

Feature test

<?php

use App\Models\Operator;
use App\Models\Telco;
use App\Services\TelcoService;
use Illuminate\Foundation\Testing\RefreshDatabase;

uses(RefreshDatabase::class);

test('a telco with operators cannot be deleted', function () {
    $telco = Telco::factory()->has(Operator::factory()->count(2))->create();

    app(TelcoService::class)->deleteIfUnreferenced($telco->id);
})->throws(RuntimeException::class);

test('an unreferenced telco is deleted', function () {
    $telco = Telco::factory()->create();

    expect(app(TelcoService::class)->deleteIfUnreferenced($telco->id))->toBeTrue();

    $this->assertDatabaseMissing('telcos', ['id' => $telco->id]);
});

test('the database itself rejects deleting a referenced telco', function () {
    $telco = Telco::factory()->has(Operator::factory())->create();

    $telco->delete();
})->throws(Illuminate\Database\QueryException::class);

Common mistakes to avoid

  • Putting the foreign key on the parent table. The constraint belongs on the child table, pointing at the parent.
  • Expecting cascadeOnDelete() to protect the parent. Cascade removes the children; restrictOnDelete() is what blocks the delete.
  • Calling an exists() check “soft deletion”. Soft deletes are the SoftDeletes trait and deleted_at column; an existence check is application-level validation.
  • Checking without a transaction. Without lockForUpdate() and the database constraint, a concurrent insert can slip between the check and the delete.

Our network