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


there 2 eloquent models in project: app\storedfile , app\storedimagesize.

the storedfile model responsible keeping uploaded files info. if uploaded file image, 2 thumbnails stored in storage , attributes in db (storedimagesize model).

relationships below:

storedfile.php:

public function sizes() {     return $this->hasmany('app\storedimagesize'); } 

storedimagesize.php:

public function originalimage() {     return $this->belongto('app\storedfile'); } 

storedimagesize has observer class (storedimagesizeobserver) has been registered through serviceprovider , works well.

the problem want delete actual file storage (in case hard disk) when deleting subsequent row database.

storedimagesizeobserver.php:

public function deleting(storedimagesize $file) {     storage::delete($file->server_url); } 

the logic this:

$file = storedfile::find(1); $file->sizes()->delete();    // delete related rows 'storedimagesize' not files storage $file->delete() 

actually never hits deleting method storedimagesizeobserver class laravel documentation says:

when executing mass delete statement via eloquent, deleting , deleted model events not fired deleted models. because models never retrieved when executing delete statement.

so, how should tackle situation? solution or recommendation appreciated.

in storedfile model add following method, have tow choices :

  • the first :

    protected static function boot() {     parent::boot();     static::deleting(function(storedfile $filetodelete) {         foreach ($filetodelete->sizes $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 observer storedfile model not storedimagesize, because said doc delete event not cascaded storedimagesize elements ! , same above in deleting method of storedfileobserver :)


Comments

Popular posts from this blog

networking - Vagrant-provisioned VirtualBox VM is not reachable from Ubuntu host -

c# - ASP.NET Core - There is already an object named 'AspNetRoles' in the database -

ruby on rails - ArgumentError: Missing host to link to! Please provide the :host parameter, set default_url_options[:host], or set :only_path to true -