Company. The company has one-to-many products. When you delete a company, you must delete all related products and their images ! The goods themselves are deleted from the database as needed, but the event is not picked up (the message "OK" is not displayed)! Tried through Events - also does not work. Through the Observer it looks like this:

Company deletion method:

public function destroy($id) { $company = Company::findOrFail($id); // удаляем связанные товары $company->goods()->delete(); // удаляем компанию $company->delete(); return redirect()->route('...'); } 

Communication in the company model:

 public function goods() { return $this->hasMany('App\Models\Good', 'company_id' , 'id'); } 

Product removal method:

 public function destroy($id) { $good = Good::findOrFail($id); // удаление товара + вызов Observer $good->delete(); return redirect()->route('...'); } 

Register Observer in AppServiceProvider:

 public function boot() { parent::boot(); Good::observe(GoodObserver::class); } 

Observer code:

 class GoodObserver { public function deleting(Good $good) { dd('OK'); // вывод сообщения об удалении } } 

    1 answer 1

    In general, calling $company->goods()->delete(); could not do.
    If you have created foreign keys and cascade deletion takes place, the connected elements will be deleted automatically.
    In the create_goods_table migration create_goods_table it looks like this:
    $table->foreign('company_id')->references('id')->on('сompanies')->onDelete('cascade'); .
    Well, I do the following by deleting pictures:
    In the Good model, we override the boot method.

     protected static function boot() { parent::boot(); static::deleting(function($good) { unlink($good->imgPath); }); } 
    • Cascading deletion is good, but like when deleting a company, delete all products along with their pictures, avoiding any foreach (...) {} - MixJay
    • Well, yes, I agree. Then leave your code + add function boot to the product model. - sepgg