我想上传多个图片并将不同的文件名保存到数据库。
我有一个HTML代码:
<input type="file" id="upload_file" name="image[]" multiple/>
和数据库表:
id
image1
image2
image3
image4
image5
created_at
updated_at
是否可以这样?
答案 0 :(得分:0)
image[]
是一个数组。您可以通过这种方式将数组元素存储在不同的列中:
public function store(Request $request)
{
$model=new Model();
$model->image1=$request->image[0];
$model->image2=$request->image[1];
$model->image3=$request->image[2];
...
$model->save();
}
正常方式:
$image=$_POST['image'];
INSERT INTO table (image1,image2,image3...)VALUES('$image[0]','$image[1]','$image[2]...);
答案 1 :(得分:0)
我认为正确的方法是使用相应的表创建Image
模型,然后设置与其他模型的关系。类似的东西:
public function store(Request $request)
{
$model = new RelatedModel(); // This is a related model example
$images = $request->file("image.*");
foreach($images as $uploadedImage)
{
$path = $uploadedImage->store('path/images', 'local'); // disk can be null, it will then use the default disk in filesystems.php
$image = new Image();
// A way you want to use to give the image a name
$image->name = $this->generateName();
$image->path = $path;
// Where relatedModel is the method on Image model defining a belongsTo relation for example with RelatedModel
$image->relatedModel()->associate($model);
$image->save();
}
}
我不知道你为什么要按照问题中指定的方式保存图片。但如果你坚持,你必须添加新的字段
id | image1 | image1_name | image2 | image2_name ...
然后在你的代码中:
public function store(Request $request)
{
$model=new Model();
// This is a function you would make to generate a different name than the path
$model->image1_name = $this->generateName();
$model->image1 = $request->file("image.0");->store('path/images', 'local');
$model->image2_name = $this->generateName();
$model->image2 = $request->file("image.1");->store('path/images', 'local');
// ...etc.
$model->save();
}