将多个图像路径存储到 Laravel 中的数据库中

Store multiple image paths into database in Laravel

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

我想将所有路径分别存储到数据库中,以便我可以访问它们 Blade。我该怎么做?

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。 PHP7.4.

你需要做一个数组:

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
    }
}

这样试试 -

public function multiStepStore(Request $request)
    {
        $images[]= Null; // $images array
        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));
                array_push($images, $filepath);  
            }
            $store_seller = new Sellers();
            $store_seller->img_path = $filepath;
    
        dd($images); //It will returns array with 3 images.
        }
    }