pmusa
1 week ago
179
9
Laravel

You can delete() over and over something already deleted...

Posted 1 week ago by pmusa

This following bothers me: Consider a Post model which uses SoftDeletes trait. You can actually do the following as many times as you want:

// some code 
$post->delete();
$post->delete();
$post->delete();
// some code

why does not this throw an error by default? how to avoid this?

In fact, you can do the same with the restore() method!

The reason why this bothers me is because this will run through a model Observer perfectly fine for the following events: deleted and restored which will trigger unwanted stuff, since you should not be able to softdelete something that is already softdeleted (and not be able to restore something that is already restored).

Quick fix : I guess I would need to wrap my whoooole code and delete() operations the following way now :

if (! $post->trashed()) {
    $post->delete();
}

which is absurd.

I figured this out while writting tests.

Is this normal and why? Thanks

Please sign in or create an account to participate in this conversation.