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

sebastian.virlan's avatar

Determine if is a soft delete in a event handler Laravel

I have this event handler:

protected static function boot() {
    parent::boot();

    static::deleting(function($user) { // before delete() method call this
        $user->comments()->delete();

    });
}

When I use $user->forceDelete(); and $user->delete(); this event is triggered and delete all comments. This is not ok because I want this event to be triggered only on $user->forceDelete();. In my case the other tables does not have soft delete implemented

0 likes
7 replies
pmall's avatar

Why do you both soft delete and hard delete users? Choose one way and act accordingly.

usman's avatar
usman
Best Answer
Level 27

@sebastian.virlan it is simple, you can check for the forceDeleting === true on the received model inside the event handler, here is the code:

protected static function boot() {
    parent::boot();

    static::deleting(function($user) {
        if($user->forceDeleting === true) {
            $user->comments()->delete();
        }
    });
}

Hope this helps.

///Updated///

3 likes
pmall's avatar

Usman answer is cool but you should really worry about aving a table that can both be soft and hard deleted. This is almost a nonsense.

svl_comyoo's avatar

Why would it be nonsense to have both hard and soft delete on the same model? I often use this to feature a trashbin functionality.

The only thing it currently lacks is a way to determine soft and hard delete in the deleted event.

Jam0r's avatar

General question, why is it considered bad practice to use both soft and force delete?

I'm heading that way at the moment with one of my models.

I want to soft delete the item when i'm finished with it (which could be months or years later) and want to preserve all the relations and history with said item.

If I create an item but don't require it before it starts, I want to force delete it along with all it's relations

BARNZ's avatar

Sorry old question but google got me here.

Laravel 5.4+ the property is protected now, so use isForceDeleting().

static::deleting(function($user) {
    if ($user->isForceDeleting()) {
        $user->comments()->delete();
    }
});

And as others have said, this example is a bit superfluous as proper database fkey cascade rules will take care of this for you.

In my case it was to check if soft deleting a user then I want to soft delete some of their immediate relations as well.

5 likes

Please or to participate in this conversation.