Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Moe's avatar
Level 6

SoftDelete and cascade

Is there a way to 'delete' (softdelete) or 'set null' related models when deleting (softdelete) the parent model automatically?

0 likes
8 replies
mstnorris's avatar

Yes, set the relevant foreign keys in the database migrations.

$table->foreign('category_id')->references('id')->on('categories')->onDelete('cascade'); // or SET NULL
Moe's avatar
Level 6

I already have that, but it does not work when using softdeletes.

mstnorris's avatar

I wasn't aware of that, but come to think of it, I suppose that makes sense. I suppose you could always do a check when displaying the parent to ensure that the child isn't deleted.

shxfee's avatar

If you are soft deleting you probably wouldn't need to remove the relationships.

If you could elaborate on what you are trying to do, maybe someone could help you better.

Moe's avatar
Level 6

Yeah it make sense, but it should be nice that when the "deleted_at" field of the parent is set, that that same field of his child's will also be set when the relation is set "cascade on delete".

1 like
jekinney's avatar

Soft deletes doesn't actually delete anything. It just sets a time stamp in the table. Adds some methods so on the parent model query that row will not be set in the query results.

So if you want to cascade to the relationships you will have to actually delete the record or manually delete each relationship. Look at the docs for model events or set a function that will loop through relationships when the delete column is set.

Keep in mind deleting related data on a soft delete defeats the purpose of using soft deleting.

pmall's avatar
pmall
Best Answer
Level 56

Use model observer to delete the children. You have to iterate over each child if you want them to also fire their deleting observers.

class Parent extends Model
{
    public function boot ()
    {
        parent::boot();

        self::deleting(function (Parent $parent) {

            foreach ($parent->children as $child) $child->delete();

        });
    }
}
1 like

Please or to participate in this conversation.