2016-04-26 32 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