Soft Delete and relationships in Laravel 4

Asked

Viewed 479 times

3

I wonder if there is any way to use soft delete but check if there are relationships/data/records linked to the record that will be deleted before deleting.

Of course, using only Laravel himself.

So, how to check relationships automatically before running soft delete?

  • The relationships in the model or at the db level? I confess that I was curious about the behavior of the model in these cases

  • In model.... how do I make Laravel identify relationships and not allow deletion, even if it is soft delete.

2 answers

1


I already needed this in a project and what I did was to perform a search before performing soft-delete. In my case it was quiet because only 2 tables had relationship with the one that was 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 observable pattern.

Create this class with an array of templates that should be consulted when soft-delete is run. Each template shall be inserted in this class when instantiated/read.

One way for the model to be inserted, in Laravel, is to create a Registry and at the time of registration perform the insertion.

Sorry I do not pass example code because I will not be able to do it at the moment, I hope the idea helps, because Laravel does not have this as standard.

  • For now it is my only solution too. I believe it will be the way. Anyway thank you.

0

You can use Model Events so you can call a method and do the checks you want, but I don’t know if the Aravel itself doesn’t do 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: https://stackoverflow.com/questions/17243637/laravel-4-cascading-soft-deletes

Browser other questions tagged

You are not signed in. Login or sign up in order to post.