产品图片更新

时间:2019-09-06 12:57:53

标签: laravel

我无法使用以下代码更新多张图片。

  • 如何更新多张图片?
 if (count($request->product_image) > 0) {
  $i = 0;
  foreach ($request->product_image as $image) {       
    if (File::exists('images/products/'.$product->image)) {
        File::delete('images/products/'.$product->image);
    }
    $img = time() . $i .'.'. $image->getClientOriginalExtension();
    $location = 'images/products/' .$img;
    Image::make($image)->save($location);
    $product_image = ProductImage::find($id);
    $product_image->product_id = $product->id;
    $product_image->image = $img;
    $product_image->save();
    $i++;
  }
}

2 个答案:

答案 0 :(得分:0)

这就是我在项目中所做的事情。

formatted

您也可以参考How to upload multiple image in laravel

答案 1 :(得分:0)

这就是我添加多个图像的方式: 我的刀片文件:

<form role="form" action="{{route('home.store')}}" enctype="multipart/form-data" method="post">
   <div class="col-lg-12">
    <div class="form-group">
     Images
     <input type="file" name="banner[]" class="form-control" id="image" multiple required>
   </div>
</form>

控制器存储功能:

public function store(Request $request) {

 if($request->hasfile('banner')) {
  foreach($request->file('banner') as $image){
   $filename=time().'_'.$image->getClientOriginalName();
    $image->move(public_path().'/images/', $filename);
    $data[] = $filename;
            }
        }
 $property = new Property;
 $property->banner=json_encode($data);
 $property->save();
}

在刀片文件上显示图像

@foreach($properties as $property)
 @foreach(json_decode($property->banner, true) as $images)
  <div class="item">
   <img src="{{asset('images')}}\{{$images}}">
  </div>
 @endforeach
@endforeach

更新功能:

public function updateapartment(Request $request, $id) {
   if($request->hasfile('banner')) {
      $del = Property::findorfail($id);
       $image_path = "images/".$del->banner;  // Value is not URL but directory file path
        if(File::exists($image_path)) {
            File::delete($image_path);
        }
        $del->delete();
      foreach($request->file('banner') as $image){
        $filename=time().$image->getClientOriginalName();
        $image->move(public_path().'/images/', $filename);
        $data[] = $filename;
            }
  $up = Property::findorfail($id);
  $up->banner=json_encode($data);
  $up->save();
        }
    }

}