Laravel 5.4 上传多个图像并将文件名保存到数据库中



我在数据库中插入上传图像的文件名时遇到问题。我的图像上传很成功,但是,在我的数据库中保存图像的文件名时,我遇到了问题。当我执行代码时,只有一个图像文件名成功保存在我的数据库中。

这是我的代码:

<form action="{{ route('admin.pictures') }}" method="post" enctype="multipart/form-data">
<input required type="file" id="images" name="images[]" multiple />
</form>

控制器:

$input=$request->all();
$images=array();
if($files=$request->file('images')){
foreach($files as $file){
$name=$file->getClientOriginalName();
$file->move('image_files',$name);
$images[]=$name;
}
}
DB::table('product_images')->insert(array(
'product_image'=>  implode("|",$images),
'product_id'=>$product_id
));

我只是从浏览互联网时复制了代码。我需要循环插入表吗?因为当我尝试此代码时,我选择了 3 张图像,并且三张图像已成功上传,但第一张图像的文件名是唯一保存在我的数据库中的图像,我希望将 3 张图像文件名插入到数据库中。

$images[]=$name; 

这就是为什么只保存第一张图像的原因。 尝试计算已上传的图像数量并递增。

$i = 0; foreach($files as $file){ $name=$file->getClientOriginalName(); $file->move('image_files',$name); $images[$i++]=$name; }

最新更新