Soft Delete and relationships in Laravel 4

3

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?

    
asked by anonymous 01.08.2014 / 22:00

2 answers

1

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.

    
05.08.2014 / 15:56
0

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

    
18.08.2014 / 03:58