首页 > 解决方案 > 在 Laravel 中将多个图像路径存储到数据库中

问题描述

我已经在我的网站上形成了。在众多字段中,有一个字段允许用户上传多张图片。我想将所有图像的路径保存到数据库中,以便可以在刀片文件中显示它们。我可以上传图像,图像存储到我的本地存储中,但问题是我只有一个路径,并且保存到数据库中。

我想将所有路径分别存储到数据库中,以便我可以为 Blade 访问它们。我怎样才能做到这一点?

<form method="POST" enctype="multipart/form-data" action="{{route('form.multiStepStore')}}">
   @csrf
   <input type="file" class="form-control" name="photos[]" multiple />
......
</form>

控制器

public function multiStepStore(Request $request)
{
    if($request->hasFile('photos')) {
        $allowedfileExtension = ['jpg', 'png', 'jpeg'];
        $files = $request->file('photos');
        foreach ($files as $file) {
            $filename = $file->getClientOriginalName();
            $extension = $file->getClientOriginalExtension();
            $filepath = $filename.'.'.$extension;
            Storage::disk('local')->put($filename.'.'.$extension,  File::get($file));
        }
    $store_seller = new Sellers();
    $store_seller->img_path = $filepath;

    dd($filepath); //Returns only one path out of let's say 3 images
    }
}

Laravel 7. PHP 7.4。

标签: phplaravellaravel-7

解决方案


您需要制作一个数组:

public function multiStepStore(Request $request)
{
    $filepath = array(); // $filepath is now an array
    if($request->hasFile('photos')) {
        $allowedfileExtension = ['jpg', 'png', 'jpeg'];
        $files = $request->file('photos');
        foreach ($files as $file) {
            $filename = $file->getClientOriginalName();
            $extension = $file->getClientOriginalExtension();
            $path = $filename.'.'.$extension;
            Storage::disk('local')->put($filename.'.'.$extension,  File::get($file));
            $filepath[] = $path; // add new image to array
        }
    $store_seller = new Sellers();
    $store_seller->img_path = $filepath;

    dd($filepath); //Returns array with 3 images
    }
}

推荐阅读