2016-07-25 37 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