在Laravel中更新时如何删除公共/文件夹中的多个图像?

时间:2018-11-13 05:34:19

标签: php laravel laravel-5

我在数据库中使用数组保存了多个图像。例如。 img.jpg,img1.jpg,img2.jpg这是我的代码。

$this->validate($request,[
        'listing_id' => 'required',
        'images.*' => 'image|mimes:jpeg,png,jpg,gif,svg|max:2048',
        'description' => 'required',
        'features' => 'required',
        'make' => 'required',
    ]);

    $vehicles = vehicle::find($id);
    $input=$request->all();
    $images=array();
    if($files=$request->File('images')){
        foreach($files as $file){
            $name=date('mdYHis').uniqid().'.'.$file->getClientOriginalExtension();
            $file->move('uploaded-images',$name);
            $images[]=$name;
            $vehicles->images = implode(",",$images);
        }
    }else{

        $vehicles->images = $request->images_dummy;

    }

我要删除public/uploaded-images中的图像文件。 我找到了这个How to Delete Images from Public/Images Folder in laravel 5 (URL Data),但是在我的代码中却无效。

2 个答案:

答案 0 :(得分:1)

当您将图像存储为逗号分隔的列表时,只需分解字符串(产生一个数组),然后循环遍历即可删除图像。

类似的事情应该起作用:

use Illuminate\Support\Facades\Storage;

$images = explode(",", $vehicles->images);

foreach ($image as $images) {
    Storage::delete("uploaded-images/{$image}");
}

如果您更改了代码以将图像名称存储为图像的实际路径(即uploaded-images/img.jpg,uploaded-images/img1.jpg,则可以将其更改为更简单:

use Illuminate\Support\Facades\Storage;

$images = explode(",", $vehicles->images);
Storage::delete($iamges);

这两个示例都可以在Laravel docs中找到。

答案 1 :(得分:1)

您应该尝试以下操作:

use File;

$images = explode(",", $vehicles->images);

foreach($images as $image){

   $image_path = public_path().'/images/'.$image;

   if(File::exists($image_path)) {
    File::delete($image_path);
   }
}