【问题标题】:Multiple images upload not working Laravel多张图片上传不起作用 Laravel
【发布时间】:2019-12-12 11:20:08
【问题描述】:

我正在尝试将多张图像存储到数据库中,但它只存储一张图像。我没有看到任何错误。我试过this,但它将图像存储在公用文件夹中,我希望将图像存储在数据库中。我怎样才能解决这个问题?任何帮助将不胜感激。

控制器

   if($request->hasFile('files')){
        $files = $request->file('files');
        foreach ($files as $file) {
            $filename = $file->getClientOriginalName();
            $images = $file->store('public/photos');
        }
  }

        ProductsPhoto::create([
            'product_id' => $product->id,
            'filename' =>  $images
        ]);

刀片

   <input type="file" name="files[]">

【问题讨论】:

  • multiple 添加到输入中,看看是否会有所改变。如果变量实际上有多个项目,请在将变量设置为 ese 后尝试执行 dd($files);
  • 所有图像都存储到 public/photos 文件夹中,但不是将所有图像名称存储在数据库中。这是你的问题吗?
  • 这并没有改变事情@MatthiasS
  • 不,它只在数据库中存储一个图像我不希望图像存储在项目@Jseelb
  • 但是:$images = $file-&gt;store('public/photos'); 这实际上是将文件存储在磁盘上。您在数据库中存储的只是文件的路径。

标签: php laravel laravel-5


【解决方案1】:

我在您的代码中看到一个问题,您正在正确移动图像,但将其存储在循环之外的数据库中,这只会将循环的最后一次迭代存储在数据库中,您可以使用此代码将多个图像存储在数据库中

if($request->hasFile('files')){

    $store_file = [];
    $files = $request->file('files');
    foreach ($files as $file) {
        $filename = $file->getClientOriginalName();
        $images = $file->store('public/photos');

        $store_file[] = [

            'product_id' => $product->id,
            'filename' =>  $images
        ];
    }

    ProductsPhoto::insert($store_file);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-10-24
    • 2022-09-29
    • 1970-01-01
    • 2019-09-05
    • 2018-04-28
    • 2021-09-20
    • 2015-04-23
    • 2020-10-07
    相关资源
    最近更新 更多