How to perform an action based on Eloquent 'deleting' event when executing a mass delete statement in Laravel 5.4?

In the StoredFile model add the following method, you have two choices :

  • the first :

      protected static function boot() {
          parent::boot();
          static::deleting(function(StoredFile $fileToDelete) {
              foreach ($fileToDelete->sizes as $size)
              {
                  $size->delete();
              }
    
              $fileToDelete->delete()
          });
      }
    
  • The second :

      protected static function boot() {
          parent::boot();
          static::deleting(function(StoredFile $fileToDelete) {
              $size_ids = $fileToDelete->sizes()->lists('id');
              StoredImageSize::whereIn($size_ids)->delete();
    
              $fileToDelete->delete()
          });
      }
    

Or create an observer for the StoredFile model not for the StoredImageSize, because as you said about the doc the delete event will not be cascaded for StoredImageSize elements ! And do the same as above in the deleting method of StoredFileObserver :)