如何在laravel中以单一形式从两个不同的文件上传字段上传多个图像?

时间:2017-04-23 09:11:18

标签: laravel

如何从表单中的两个单独的文件上传选项传递多个图像文件,然后存储到数据库中?这是我的架构和控制器代码。

Schema::create('images', function (Blueprint $table) {
        $table->increments('image_id');
        $table->increments('book_id')->unsigned();
        $table->string('coverPageImage');
        $table->string('previewPageImage');
        $table->timestamps();

  });

表单字段:BookID,coverPageImage的文件上传,文件上传 previewPageImage。 coverPageImage和previewPageImage都传递了多个图像。

我能够将图像上传到文件夹并保存到数据库以进行单个文件上传。

$product_images = $request->file('coverPageImage');
foreach($product_images as $product_image){
   $coverImage_name = $product_image->getClientOriginalName();
   $upload = $product_image->move('images', $coverImage_name); 
   Image::create([
     'book_id' => $book_id,
     'cover_images' => $coverImage_name
      ]);
}

$preview_pages = $request->file('previewPageImage')
foreach($preview_pages as $preview_image){
   $previewImage_name = $preview_image->getClientOriginalName();
   $upload = $preview_image->move('images', $previewImage_name); 
      Image::create([
        'book_id' => $book_id,
        'preview_images' => $previewImage_name
      ]);
    }

我想使用以下方式:

 Image::create([
    'book_id' => $book_id,
    'cover_images' => $coverImage_name,
    'preview_images' => $previewImage_name
 ]);

但是我在使用foreach循环时遇到了两个不同的文件上载。任何建议或提示。

1 个答案:

答案 0 :(得分:1)

如果您确定$coverImage_name$previewImage_name之间始终存在1:1的关系,那么您可以将它们推入数组,循环数组,并从中创建图像内。

$images = [];
$product_images = $request->file('coverPageImage');
foreach ($product_images as $idx => $product_image){
    $coverImage_name = $product_image->getClientOriginalName();
    $upload = $product_image->move('images', $coverImage_name);
    $images[$idx]['cover_image'] = $coverImage_name;  
} 

$preview_pages = $request->file('previewPageImage')
foreach($preview_pages as $idx => $preview_image){
    $previewImage_name = $preview_image->getClientOriginalName();
    $upload = $preview_image->move('images', $previewImage_name); 
    $images[$idx]['preview_image'] = $previewImage_name;
}

foreach($images as $idx => $arr) {
    Image::create([
        'book_id' => $book_id,
        'cover_images' => isset($arr['cover_image']) ? $arr['cover_image'] : null,
        'preview_image' => isset($arr['preview_image']) ? $arr['preview_image'] : null
    ]);
}