2017-01-13 118 views
0

我需要將多個圖像上傳到服務器。如果圖像存在於數據庫更新名稱中,請上傳新的。否則在數據庫中創建新記錄。 腳本我上傳了新圖片,但沒有更新現有圖片。從索引中獲取項目Laravel 5

if ($request->hasFile('images')) { 
    foreach ($request->file('images') as $key => $image) { 
     $filename = time() . $image->getClientOriginalName(); 
     $image->move('img/products', $filename); 

     if (isset($product->images[$key])) { 
      $result = $product->images[$key]->update([ 
       'name' => $filename 
      ]); 
      dd($result); 
     } else { 
      $product->images()->create([ 
       'name' => $filename 
      ]); 
     } 
    } 
} 
+0

你也應該顯示你的輸入表單,這樣我們就可以瞭解什麼類型的請求要進入 –

+0

'$ product'或者如何用集合填充它? –

+0

輸入類型文件。還有什麼? –

回答

0

應該這樣

if ($request->hasFile('images')) { 
     foreach ($request->file('images') as $key => $image) { 
      $filename = time() . $image->getClientOriginalName(); 
      $image->move('img/products', $filename); 

      $product->images->updateOrCreate(['id' => $key], ['name' => $filename]); 
     } 
    } 

來完成請並不是說我認爲$鍵是ID iamges意味着你輸入應該被命名爲這樣

<imput name="images['Id_of_image_in_databse']" type="file" /> 
+0

從哪裏我會得到id? –

+0

那爲什麼我首先要求你提供你的代碼表格 –

2

使用updateOrCreate()方法來代替整個if ... else子句:

$product->images->updateOrCreate(['id' => $key], ['name' => $filename]); 
+2

upvote for updateOrCreate()'暗示...... –

+0

是輸入文件的索引,而不是id –

+0

鍵是輸入的數目,如果使用了第二個輸入 - 更新第二個圖像在db –

0

首先,你需要確保對代碼的結果,將下面的代碼之前if ($request->hasFile('images')) {行:

print('<pre style="color:red;">Uploaded image:: '); 
print_r($request->file('images')); 
print('</pre>'); 


print('<pre style="color:red;"> Product Image:: '); 
print_r($product->images); 
print('</pre>'); 
exit; 

這是不能不回答的一部分!所以讓我知道上面代碼的結果。

1

您還可以使用wonderfull收集方法laravel必須檢查集合是否包含特定項目/項。請查看https://laravel.com/docs/5.3/collections#method-get以從集合中檢索按鍵的項目。如果該項目不存在,則返回null。您可以進行如下檢查:

if(null !== $product->images()->get($key)){ 
    // update 
    // remove old image 
} else { 
    // create 
} 

當您處於更新方法中時,也可以從服務器上刪除舊映像。

相關問題