1

I am reading up on laravel softdelete and restore cascade here: Laravel 5: cascade soft delete

where a user said:

You should use Eloquent events for this.

Offers::deleted(function($offer) {
    $offer->services()->delete();
});
Offers::restored(function($offer) {
    $offer->services()->withTrashed()->restore();
});

He did not mention where to place this code, I am interested in listening for eloquent deleted and restored events. Where can I put this code? Can I listen for it in the model class? If not where to place it?

Community
  • 1
  • 1
niko craft
  • 2,893
  • 5
  • 38
  • 67

1 Answers1

2

I think...

<?php
class Attribute extends Model implements Transformable
{
//....
protected static function boot() {
    parent::boot();

    static::deleting(function($model) {
        foreach ($model->attributeValue()->get() as $attributeValue) {
            $attributeValue->delete();
        }
    });

}

Or example:

class BaseModel extends Model
{
    public static function boot()
    {
        static::creating(function ($model) {
        // blah blah
        });

        static::updating(function ($model) {
        // bleh bleh
        });

        static::deleting(function ($model) {
        // bluh bluh
        });

       parent::boot();
   }
}
Globsecure
  • 132
  • 2
  • 11