Laravel - 多张图片上传

时间:2018-04-06 12:08:30

标签: image laravel laravel-5 laravel-4

在我的项目中,我有一个名为products的表。每个产品都可以附加多个图像。所以我创建了一个名为Images的数据库表,在该表中我放了以下内容:

 public function up()
{
    Schema::create('images', function (Blueprint $table) {
        $table->increments('id');
        $table->integer('product_id');
        $table->string('image');
        $table->timestamps();
    });
}

现在我知道如何上传单个文件,我自己想出来了。但现在我希望能够上传多个图像并将所有上传的图像附加到创建的产品中。在我的表单中,我有一个看起来像这样的输入。

<div class="form-group mb-3">
 <label for="image">Pictures</label>
 <input type="file" name="image[]" id="image" class="form-control" multiple>
</div>

这使用户能够选择多个图像。我在我的请求中有一个包含所有图像的数组。该数组看起来像这样。 enter image description here

如何使其成为可能,以便images表格将填充所有选定的图像。这就是我管理单个图像的方式:

 if( $request->hasFile('thumbnail') ) {
        $thumbnail = $request->file('thumbnail');
        $filename = time() . '.' . $thumbnail->getClientOriginalExtension();

        Image::make($thumbnail)->resize(286, 180)->save( public_path('/uploads/' . $filename));
        $data['thumbnail'] = $filename;
    }

如何使用所选图像执行多张图像并填充图像表?

修改

存储库产品

public function createProduct($data, $chosenType)
{


    $product = new Product();

    $product->productable_type = $data['productable_type'];
    $product->productable_id = $chosenType;
    $product->name = $data['name'];
    $product->description = $data['description'];

    $product->thumbnail = $data['thumbnail'];




    $product->price = $data['price'];
    $product->periodically_price = $data['periodically_price'];
    $product->period_id = $data['period_id'];

    $product->save();

    // THIS DOESNT WORK. IM TRYING TO MAKE IT WORK
    foreach($data['image'] as $image) {
        $image = new Image();

        $image->product_id = $product->id;
        $image->image = $data['image'];
    }

    dd($data, $product);


    return $product;
}

1 个答案:

答案 0 :(得分:0)

像这样循环上传的图片

foreach( $request->file('image') as $image ){
  $filename = time() . '.' . $image->getClientOriginalExtension();
  Image::make($image)->resize(286, 180)->save( public_path('/uploads/' . $filename));
}
相关问题