【问题标题】:Laravel - Storing multiple images in the database in Single RowLaravel - 在数据库中以单行存储多个图像
【发布时间】:2019-04-27 02:25:55
【问题描述】:

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

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

控制器

 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>

【问题讨论】:

  • 这个问题解决了吗?
  • 这里还没有解决我的问题点击这里请link
  • 看起来您添加了另一个扩展问题。但是这个问题呢?

标签: php mysql arrays laravel


【解决方案1】:

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

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

当你想读取值时,你会这样做:

json_decode($citi->city);

现在,我建议做一组图像并对其进行编码,然后解码即可:

json_decode($obj->city, TRUE);

你会得到你的数组回来

【讨论】:

    【解决方案2】:

    您应该将图像存储在循环中。 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');
    }
    

    【讨论】:

      猜你喜欢
      • 2014-09-12
      • 2020-11-15
      • 2016-09-05
      • 2022-11-14
      • 2017-01-05
      • 2019-12-27
      • 2021-10-21
      • 1970-01-01
      • 2019-02-26
      相关资源
      最近更新 更多