Laravel boot method

Viewed 10270

In my models I've setup boot methods so when I softdelete a record the related records are softdeleted aswell. Like this:

Company.php

protected static function boot()
    {
        parent::boot();
        static::deleting(function($company) {
            $company->department()->delete();
        });
    }

Department.php:

 protected static function boot()
    {
        parent::boot();
        static::deleting(function($department) {
            dd('test');
        });
    }

So when I want to softdelete a company the departments should also be softdeleted. But when I dd in static::deleting(Department.php) this is not reached. When I dd like this:

Department.php

protected static function boot()
    {
        parent::boot();
        dd('test');
        static::deleting(function($department) {
        });
    }

Result is test

What am I doing wrong here?

2 Answers

in Company Model:

  1. Describe relation between company and department:
public function departments(){
    return $this->hasMany(Department::class);
}
  1. Iterate each department for deleting in method boot() within Company Model:
protected static function boot(){
    parent::boot();
    static::deleting(
        function($company){
        $company->departments()->
            each(fn($department)=>$department->delete());
    });
}

In Department Model: describe relation between department and company

public function company(){
    return $this->belongsTo(Company::class);
}
Related