【问题标题】:backpack for laravel deleting imagelaravel 删除图片的背包
【发布时间】:2017-09-06 14:53:49
【问题描述】:

当尝试删除图像时,我需要将其从磁盘中完全删除

功能:

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;
    }

图片路线: 数据库:

删除映像时,没有任何变化,需要帮助从磁盘物理删除映像。

【问题讨论】:

  • 你是使用-&gt;delete()函数还是手动设置url为null
  • 我正在使用删除来物理删除图像
  • 我对另一种类型的文件 pdf 有相同的方法,奇怪的是它可以删除文件并在数据库上设置 null。
  • \Storage::disk()->delete('uploads/equipos'.$this->url);试过这个没有成功

标签: laravel laravel-backpack


【解决方案1】:

TLDR;上传后检查目标文件权限,删除前也尝试dump($this-&gt;url),以确保使用的磁盘路径正确

示例:

只要您正确定义了您的字段,背包应该能够自动管理所有内容。例如,处理客户端图像,我将其作为字段:

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

然后,在模型中

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");
    }
}

仅此而已,背包可以解决所有问题。

您唯一需要考虑的是,如果您删除模型(在我的示例中删除客户端),您还需要自己处理文件删除。这可以在模型的boot 方法中通过deleting 事件完成。

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

当您将$disk 和字段value 传递给它时,它将毫无问题地删除文件,无需指定路径,因为它将包含在$value

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-12-19
    • 2020-11-16
    • 1970-01-01
    • 1970-01-01
    • 2014-10-03
    • 2016-11-25
    • 2012-02-10
    • 2021-08-22
    相关资源
    最近更新 更多