2016-07-25 61 views
2

我正在使用Laravel 5構建一個應用程序,我想在逗號分隔的數組中插入多個圖像網址。這將被放置在數據庫的一列中。這些文件已成功上傳到我的AWS S3存儲桶,但它現在是數據庫的輸入。我嘗試使用Laravel的array_add幫助程序,但我得到一個錯誤,指出我缺少參數2.我想知道如何能夠實現這一點。我目前的替代解決方案是將圖像與帖子ID並使用關係將它們連接在一起。Laravel 5:將圖像網址插入列作爲數組

僅供參考:我打算放置圖像的列是picgallery,插入操作是使用$ newproperty ['picgallery']變量完成的。

public function store(Request $request) 
{ 
    //establish random generated string for gallery_id 
    $rando = str_random(8); 

    //input all data to database 
    $data = $request->all(); 

    $newproperty['title'] = $data['title']; 
    $newproperty['address'] = $data['address']; 
    $newproperty['city'] = $data['city']; 
    $newproperty['province'] = $data['province']; 
    $newproperty['contact_person'] = Auth::user()->id; 
    $newproperty['gallery_id'] = $rando; 
    $newproperty['property_description'] = $data['description']; 

    if($request->hasfile('images')) { 
     $files = $request->file('images'); 

     //storage into AWS 
     foreach ($files as $file) { 
      $uploadedFile = $file; 
      $upFileName = time() . '.' . $uploadedFile->getClientOriginalName(); 
      $filename = strtolower($upFileName); 

      $s3 = \Storage::disk('s3'); 
      $filePath = 'properties/' . $rando . '/' . $filename; 

      $s3->put($filePath, file_get_contents($uploadedFile), 'public'); 

      $propicurl = 'https://s3-ap-southeast-1.amazonaws.com/cebuproperties/' . $filePath; 

      $array = array_add(['img'=> '$propicurl']); 

      $newproperty['picgallery'] = $array; 

     } 
    } 

    Properties::create($newproperty); 

    return redirect('/properties'); 
} 

回答

0

array_add要求3個參數

$陣列= array_add($陣列, '鍵', '值'); (https://laravel.com/docs/5.1/helpers#method-array-add

例如

$testArray = array('key1' => 'value1'); 
$testArray = array_add($testArray, 'key2', 'value2'); 

,你會得到

[ 
    "key1" => "value1", 
    "key2" => "value2", 
] 

您可能無法在這種情況下使用array_add。

我認爲,爲了解決您的問題,解決您的foreach循環是這樣的

//storage into AWS 
// init the new array here 
$array = []; 
foreach ($files as $file) { 
     $uploadedFile = $file; 
     $upFileName = time() . '.' . $uploadedFile->getClientOriginalName(); 
     $filename = strtolower($upFileName); 

     $s3 = \Storage::disk('s3'); 
     $filePath = 'properties/' . $rando . '/' . $filename; 

     $s3->put($filePath, file_get_contents($uploadedFile), 'public'); 

     $propicurl = 'https://s3-ap-southeast-1.amazonaws.com/cebuproperties/' . $filePath; 

     // change how to use array_add 
     array_push($array, array('img' => $propicurl)); 
     // remove the below line 
     // $array = array_add($array, 'img', $propicurl); 
} 

// move this assignment out of foreach loop 
$newproperty['picgallery'] = $array; 
+0

只是嘗試這樣做。有一個未定義的變量:數組錯誤。 –

+0

你需要把數組初始化在foreach循環之上 $ array = []; 請覈對答案中的最新代碼 – gie3d

+0

再來想一想。我們在同一個數組中插入了一個重複鍵,這意味着最終您將得到一個只有1個元素的數組。我想我們可以使用array_push來代替。我會更新我的答案 – gie3d