Search code examples
laravelvoyager

Laravel Voyager BREAD Image Edit and Delete Issue


I have ran into a problem with image upload using voyager BREAD System. If I delete or update an image using BREAD the old image not replaced or deleted. It is still in the storage directory. I was using latest version of voyager with laravel 5.5. Is there any solution to this problem? Thank you in advance.


Solution

  • There is no public function deleteBreadImages($data, $rows) {...} anymore
    in Laravel Voyager 1.2 class file
    vendor/tcg/voyager/src/http/controllers/VoyagerBreadController.php

    After two days of googling same issue I figured out the Hard Solution...
    in my case image field name is img and model name is Company
    code is executed while the Model BREAD is updating

    Works on Voyager 1.2 Hope it helps ))

    use Storage;
    
    class Company extends Model
    {
        public static function boot()
        {
            parent::boot();
    
            static::updating(function($model)
            {   
                // Check if Old File Exists
                $oldFileExists = Storage::disk('public')->exists($model->original['img']);
    
                // If Old File Exists DELETE it, else Continue Adding New Image
                if($oldFileExists)
                {
                    //Get File Extension:: .jpg .png .gif
                    $fileExt = substr(strrchr($model->original['img'], "."), 0);
    
                    //If File is not .GIF
                    if($fileExt != '.gif'){
                        // Delete Old Non-GIF Image
                        Storage::disk('public')->delete($model->original['img']);
                    }
    
                    // Find .gif , -static.gif Old Images And Delete
                    else{
    
                        // filename-static.gif
                        $staticOld = str_replace($fileExt,"-static".$fileExt,$model->original['img']);
                        // Delete Old Image.gif
                        Storage::disk('public')->delete($model->original['img']);
                        // Delete Old Image-static .gif if Exists
                        if($staticOld) Storage::disk('public')->delete($staticOld);
    
                    }
                }
            });
        }
    }