Question :
I would like to know if there is any way to use soft delete but check if there are relationships / data / records attached to the record that will be deleted before deleting.
That’s clear, using only Laravel himself.
So, how to check relationships automatically before running soft delete?
Answer :
I needed this in a project and what I did was to perform a search before performing the soft-delete. In my case it was quiet because only 2 tables were related to the one being manipulated.
To work with a context where you can have n-related tables, and sometimes tables of plugins or modules that may or may not be active, you can create a class derived from the idea of the observable pattern.
Create this class with an array of templates that should be queried when soft-delete is run. Each template must be inserted into this class when instantiated / read.
One way that the template is inserted, in Laravel, is to create a register and at the time of registration perform the insertion.
I’m sorry to not pass example code because I will not have to do so at the moment, I hope the idea helps, because Laravel does not have it as default.
You can use Model Events so you can call a method and do the checks that you want, but I do not know if laravel himself does it.
User::deleting(function($user)
{
if ( ! $user->isDeleted()) return false; // se tu retorna falso ele não deleta
});
Another option is to use this
// Laravel's equivalent to calling the constructor on a model
public static function boot()
{
// make the parent (Eloquent) boot method run
parent::boot();
// cause a soft delete of a product to cascade to children so they are also soft deleted
static::deleted(function($product)
{
$product->images()->delete();
$product->descriptions()->delete();
foreach($product->variants as $variant)
{
$variant->options()->delete();
$variant->delete();
}
});
}
Source: link