backpack for laravel deleting image

1k views Asked by At

when trying to delete an image i need to remove it completely form the disk

function:

public function setUrlAttribute($value)
{  
    $attribute_name = "url";
    $disk = "public";
    $destination_path = "uploads/equipos";

    if ($value==null) {
        // delete the image from disk

       Storage::disk($disk)->delete($this->url);   //<---- fix here
        // set null in the database column
        $this->attributes[$attribute_name] = null;
    }

Image route: enter image description here the database:

enter image description here

when deleting the image, nothing changes, need help deleting the image physically from the disk.

1

There are 1 answers

0
Marcos Besteiro López On BEST ANSWER

TLDR; check for destination files permissions after upload, also try to dump($this->url) before deleting, to ensure the correct path from your disk is being used

Example:

As long as you have your field correctly defined, backpack should be able to manage everything automatically. For example, dealing with client images, I have this as the field:

$this->crud->addField([
  'name' => 'logotipo',
  'label' => "Logotipo del Cliente",
  'type' => 'image',
  'upload' => true,
  'crop' => true,
  'disk' => 'uploads',
  ], 'both');

Then, in the model

public function setLogotipoAttribute($value)
{
    if ($value==null) {
        if(isset($this->attributes["logo"])) {
            \Storage::disk($this->disk)->delete($this->attributes["logo]);
        }
        return null;
    }
    else
    {
      /* Whatever you need, I just create thumbs with a custom \Utils::thumb, you can mutate the atrribute to your needs */
      $this->attributes["logo"] = \Utils::thumb($this, $value, "logo", "academias/logos", 300, 200, "png");
    }
}

And that's all, backpack takes care of everything.

The only thing you need to take into account is, if you delete the model (deleting a client in my example), you also need to take care of the files deleting by yourself. This can be done in the boot method of the model, with a deleting event.

public static function boot()
{
    parent::boot();
    static::deleting(function($obj) {
        if (isset($obj->logo)) \Storage::disk($obj->disk)->delete($obj->logo);
    });
}

As you pass it the $disk and the field value, it will delete the file without problems, no need to specify the path, as it will be included in the $value