Welcome, I hope my blog is of some use for you!

Laravel

Force deleting event in Laravel

Laravel’s events are great! You can easily add some logic in your code for certain events in Laravel. Like creating, created updating, updated and also deleting.

However I stumbled on a use case where a needed some logic when a model was being permanently deleted. Because I was using softDelete my model the event was already fired the first time I deleted it. That didn’t mean the record was actually gone in the database, because that is what softDelete does. So in case of a trashbin for example you want to keep the data that belongs to that record like images or other files.

But when you force delete the model I do want to delete the files. So it would have been great if there was a force delete event in Laravel. It happens there is none, too bad.

Now there are other option to replicate a force delete event. Because of how softDelete works we can check if the deleted_at columns has been filled in with a date. When it’s filled we know the model has been deleted already. So we can again use the delete event.

Model::deleting(function ($model) {
        if(!$model->deleted_at) {
            // normal delete
        }else{
            // force delete -> do your thing!
        }
});

In the example above you can see how we can check when the model is being force deleted. At that moment we can do the logic need when a model is actually removed from the database.

Related posts
Laravel

No more helper functions for Laravel?

Laravel

Translatable resource routes in Laravel

Laravel

How to set logout redirect path in laravel 5.3+

Laravel

Save a model with custom attributes - Laravel 5.4+

Sign up for our Newsletter and
stay informed

Leave a Reply

Your email address will not be published. Required fields are marked *