我正在尝试在laravel中上传多张图片,并且每次上传同一张图片时都遇到问题?

时间:2018-12-06 04:28:49

标签: laravel laravel-5 laravel-5.6

问题是我的循环每次只运行并上传同一张第一张图片,而不是一个又一个地连续上传!

这是我的代码形式

{!! Form::file('photos[]', ['roles' => 'form', 'class' => 'form-control-file','multiple' => true]) !!}

这是我的控制器代码

            $files=$request->file('photos');
            foreach ($files as $file) {   
            $insert = new Images;
            $insert->youth_fashion_images_category = $request->selectproduct; 
            $destinationPath = 'uploads/products';
            $imageName = 'uploads/products/'.time().'.'.$file->getClientOriginalExtension(); 
                $insert->Save();
                $uid = $insert->id;
             $file->move($destinationPath,$imageName);
             $image = array(
                'youth_fashion_images_img' => $imageName
            );
             Images::where('youth_fashion_images_id',$uid)->update($image);    
           }


             return redirect('adminpanel/viewimages');

2 个答案:

答案 0 :(得分:0)

尝试此代码:

if($request->hasfile('photos'))
         {    
            foreach($request->file('photos') as $image)
            {                                    
                $destinationPath = 'uploads/products';
                $imageName = 'uploads/products/'.time().'.'.$image->getClientOriginalExtension(); 
                $image->move($destinationPath,$imageName);                    

                $insert = new Images;
                $insert->youth_fashion_images_category = $request->selectproduct; 
                $insert->youth_fashion_images_img = $imageName;                 
                $insert->Save();                  
            }
         }

答案 1 :(得分:0)

您应该尝试使用此代码。

if($request->hasfile('photos')) {

    foreach($request->file('photos') as $image)
    {
        $destinationPath = 'uploads/products';
        $name = 'uploads/products/'.time().'.'.$image->getClientOriginalName();
        $image->move($destinationPath, $name);  
        $data[] = $name;  
    }
}

$insert= new Images;
$insert->youth_fashion_images_img = json_encode($data);

$insert->save();

json_encode将多个图像名称插入一行。 因此,在数组$data[] = $name;中添加$ name。 我希望这会有所帮助。