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

Viewed 11175

There are 2 Eloquent models in my project: App\StoredFile and App\StoredImageSize.

The StoredFile model is responsible for keeping uploaded files info. If the uploaded file would be an image, then 2 thumbnails will be stored in storage and their attributes in DB (StoredImageSize model).

Relationships are as below:

StoredFile.php:

public function sizes()
{
    return $this->hasMany('App\StoredImageSize');
}

StoredImageSize.php:

public function originalImage()
{
    return $this->belongTo('App\StoredFile');
}

StoredImageSize has an observer class (StoredImageSizeObserver) which has been registered through a ServiceProvider and works well.

The problem is that I want to delete the actual file from storage (in my case hard disk) when deleting the subsequent row from database.

StoredImageSizeObserver.php:

public function deleting(StoredImageSize $file)
{
    Storage::delete($file->server_url);
}

The logic is something like this:

$file = StoredFile::find(1);
$file->sizes()->delete();    // it does delete all related rows from 'StoredImageSize' but not files from storage
$file->delete()

actually it never hits deleting method from StoredImageSizeObserver class as Laravel documentation says:

When executing a mass delete statement via Eloquent, the deleting and deleted model events will not be fired for the deleted models. This is because the models are never actually retrieved when executing the delete statement.

So, How should I tackle this situation? Any solution or recommendation would be appreciated.

2 Answers
Related