Askedio/laravel-soft-cascade

Model events not fired during cascade

Closed this issue ยท 7 comments

  • Laravel Soft Cacade Version: 5.5.15
  • PHP Version: 7.1
  • Database Driver & Version: MySQL Ver 14.14 Distrib 5.7.16 for osx10.11

Description

The model events (like deleting or deleted) are not fired during the soft cascade (not sure if this is intended behavior).

I want to use Observers to act on the models before they are soft deleted, but they don't get called since the events are not fired.

I am taking steps to upgrade my Laravel version, so if this is already solved (in case it isn't expected behavior) in the package's 5.6 and 5.7, that would be a relief.

Thanks for your time. Awesome package, by the way!

Steps to Reproduce

Create an Observer for a model that is going to be cascade (soft) deleted and then (soft) delete the parent model.

Edit: typo.

Code Example

ModelA.php

class ModelA extends Model
{
     use SoftDeletes;
     use SoftCascadeTrait;

     protected $dates = ['deleted_at'];

     protected $softCascade = [
         'children'
     ];

     public function children()
     {
          return $this->hasMany(ModelB::class);
     }
}

ModelB.php

{
     use SoftDeletes;

     protected $dates = ['deleted_at'];

     public function parent()
     {
          return $this->hasOne(ModelA::class);
     }
}

ModelBObserver.php

class ModelBObserver
{

    public function deleting(ModelB $model)
    {
        $model->name = 'Deleted Model';
        $model->save();
    }
}

In AppServiceProvider.php

public function boot() 
{
     ...
     ModelB::observe(ModelBObserver::class);
}

In a Test file:

/** @test **/
public function testEventsOnCascade()
{
     $modelA = new ModelA();
     $modelA->save();
     $modelA->refresh();

     $modelB = new ModelB();
     $modelB->parent_id = $modalA->id;
     $modelB->save();

     $modelA->refresh();
     $modelB->refresh();

     $modelA->delete();
     $modelB->refresh();

     $this->assertEquals('Deleted Model', $modelB->name);
}

The test fails.

@felipevfa

First of all thanks for use the package.

I will test what you comment and fix it if failing.

@felipevfa

I checked what you say and it's not working because our package do deletions with Builder for performance reasons.

Unfortunately observers only work with single Model. I will check if we can fire event on every deleted relation with model and identifiers.

It is very important enhancement

Any news on this matter?

@heikokrebs I started it few days ago but all code must be refactored to fireModelEvent can be called.
QueryBuilder executes update and is hard to track delete/restore events.

Any news on this?

@aat2703 Now I do not have time to do it. You are free to do it and create a pull request with needed changes.

Thanks for your interest on package.