2016-04-26 65 views
0

我试图用多个图像格式来更新表格字段。创建表单工作正常,但问题是当我试图更新它。Laravel 5.2 - 无法更新多个图像,未定义偏移量:0

所以这里的更新功能的控制器:

public function update(Request $request, $id) 
{ 
    $update = new Product($request->all()); 
    $product=Product::find($id); 

    $picture = ''; 
    $images = []; 
    if ($request->hasFile('images')) { 
    $files = $request->file('images'); 
    foreach($files as $file){ 
    $filename = $file->getClientOriginalName(); 
    $extension = $file->getClientOriginalExtension(); 
    $picture = date('His').$filename; 
    $destinationPath = base_path() . '\public\images/'; 
    $file->move($destinationPath, $picture); 
    $images[]=$picture; 
    } 
    } 

    if (!empty($product['images'])) { 
    $product['images'] = $images[0]; 
    $product['images2'] = $images[1]; 
    $product['images3'] = $images[2]; 
    $product['images4'] = $images[3]; 
    } else { 
    unset($product['images']); 
    } 

    $product->update($update); 
    return redirect('product'); 
} 

如果还不清楚的话,你可以看到codeshare.io

全ProductController的和更新的形式是codeshare.io 正如你所看到的,我正在使用阵列将图像插入到数据库,并且已经定义了阵列$product['images4'] = $images[3];

这是放置图片的位置。 This is where the picture was placed.

但它给我的错误:

ErrorException in ProductController.php line 149: Undefined offset: 0 

您能否提供一个更好的代码或给我解释一下关于这个错误吗?非常感谢;) 祝您有美好的一天。

回答

3

未定义,偏移当您尝试访问未上传的图片的指数出现。

To fix this problem, you should modify your code like this -

public function update(Request $request, $id) 
{ 
    $update = $request->all(); 
    $product = Product::find($id); 

    $picture = ''; 
    $images = []; 
    if ($request->hasFile('images')) { 
     $files = $request->file('images'); 
     foreach($files as $file){ 
     if (isset($file)){ 
      $filename = $file->getClientOriginalName(); 
      $extension = $file->getClientOriginalExtension(); 
      $picture = date('His').$filename; 
      $destinationPath = base_path() . '\public\images/'; 
      $file->move($destinationPath, $picture); 
      array_push($images, $picture); 
     } 
     } 
    } 

    if (!empty($product['images']) && isset($images[0])) { 
     $update['images'] = $images[0]; 
    } 
    if (!empty($product['images2']) && isset($images[1])) { 
     $update['images2'] = $images[1]; 
    } 
    if (!empty($product['images3']) && isset($images[2])) { 
     $update['images3'] = $images[2]; 
    } 
    if (!empty($product['images4']) && isset($images[3])) { 
     $update['images4'] = $images[3]; 
    } 
    unset($update['images']); 
    $product->update($update); 
    return redirect('product'); 
} 
+0

嗨,它给我'preg_replace():参数不匹配,模式是一个字符串,而替换是一个数组' –

+0

@PutriDewiPurnamasari哪一行?尝试复制并粘贴整个代码(我已经编辑并编辑) – atefth

+0

helpers.php中的ErrorException错误740行: –

0

使用print_r($image); exit;的foreach结束后,检查阵列凯和价值,并安排它

+0

它给了我'阵列([0] => 4)'' –

+0

的print_r($图像);退出;'写每个 – abhayendra