Luke Curtis

Luke Curtis

Software Developer and Project Manager

Contact Me

Easy Soft Delete Cascade in Laravel

04/03/2019 (2 months ago) | Luke Curtis

Recently I saw this tweet pop up on my timeline. It basically states how to easily restore/delete your models if you have a relationship that is soft deleted. I like this approach, but it feels a little verbose, and sometimes you may accidentally omit this from your controller or repository.

Take for example, the scenario of a Post and Comments. If a post is deleted, if you've set up your schema correctly, it should also delete the associated comments. But what about when you soft delete that post?

In Laravel world, it doesn't automatically soft delete the comment too. But, with the previous tweet you could potentially do something like this. In my experience, I prefer maintaining this sort of stuff in the model. Enter askedio's amazing laravel soft cascade package.

By adding a simple trait to your method and a variable, every time the delete method is fired on this parent model, the child models will also be soft deleted.

Our super clean soft cascade

Our super clean soft cascade

I think this approach is pretty neat but it's not without it's problems. Naturally when doing a mass delete, for example Advertisement::whereNull('user_id')->whereJobId('5')->delete(), this is an instance of a mass delete, in which the model delete event will not be fired

However, it is rare I find myself requiring a mass delete. So in practice this isn't too much of an issue, but your mileage may vary.