Laravel-在单行中将多个图像存储在数据库中

时间:2018-11-25 02:44:47

标签: php mysql arrays laravel

如何在laravel的数据库中存储多个图像?我有这段代码,但是我无法传递任何数据,它只能传递一个数据。

  

我想在我的图像行中实现这种数据库格式

enter image description here

控制器

 public function store(Request $request)
{


   //Handle File Upload
   if($request->hasFile('city')){
    // Get FileName
    $filenameWithExt = implode(' , ',$request->file('city')->getClientOriginalName());
    //Get just filename
    $filename = pathinfo( $filenameWithExt, PATHINFO_FILENAME);
    //Get just extension
    $extension =  implode(' , ',$request->file('city')->getClientOriginalExtension());
    //Filename to Store
    $fileNameToStore = $filename.'_'.time().'.'.$extension;
    //Upload Image
    $path =  implode(' , ',$request->file('city')->storeAs('public/city_image',$fileNameToStore));

}else{
    $fileNameToStore='noimage.jpg';
}

   $citi = new City;
   $citi->city =$fileNameToStore;
   $citi->save();

   return redirect('/lugar')->with('success', 'Data Inserted');
}

查看

                 <td> {{Form::file('city[]')}} </td>

2 个答案:

答案 0 :(得分:0)

您将需要对它们进行JSON编码。将该数据库字段设置为long text,然后在将值保存到数据库时执行以下操作:

$citi->city = json_encode($fileNameToStore);

当您要读取值时,将按以下方式进行操作:

json_decode($citi->city);

现在,我建议做一个图像数组并对它们进行编码,然后解码就可以了:

json_decode($obj->city, TRUE);

您将恢复阵列

答案 1 :(得分:0)

您应该将图像循环存储。 city字段是一个数组。

我修改了您的功能。让我知道我做错了什么。

public function store(Request $request)
{
    if($request->hasFile('city'))
    {
       $file = Input::file('city');
       foreach($file as $key => $part) 
       {
          $filename = $part->getClientOriginalName();
          $filenameWithExt = implode(' , ',$filename);
          $filename = pathinfo( $filenameWithExt, PATHINFO_FILENAME);
          $extension =  implode(' , ',$part->getClientOriginalExtension());
          $fileNameToStore[$key] = $filename.'_'.time().'.'.$extension;
          $path =  implode(' , ',$part->storeAs('public/city_image',$fileNameToStore[$key]));
       }
       // converting images names array to comma separate string 
       $fileNameToStore = implode (", ", $fileNameToStore);
    }else{
       $fileNameToStore = null; // if no image found then it should be null
    }

   $citi = new City;
   $citi->city = $fileNameToStore;
   $citi->save();

   return redirect('/lugar')->with('success', 'Data Inserted');
}