Laravel 8 如何在ImagesController的store方法中获取商品product_id
Laravel 商品图片上传关联product_id解决方案
你已经在上传表单中添加了product_id隐藏域,只需要修正现有代码的逻辑错误,给Image模型赋值product_id即可完成存储:
现有代码核心问题
- 表单文件上传字段名为
filenames[],但控制器中验证、读取文件时错误使用了imagenames作为字段名,导致无法获取上传文件 - 新建Image实例时没有给
product_id字段赋值,导致外键字段为空无法入库 - 读取上传文件的API调用错误,Laravel中读取上传文件使用
$request->file()方法,而非$request->image() - 模型
save()方法不需要传入自身实例作为参数
修正后的store方法代码
public function store(Request $request) { // 验证规则修正文件字段名为filenames $this->validate($request, [ 'product_id' => 'required|exists:products,id', 'filenames' => 'required', 'filenames.*' => 'mimes:png,jpeg,jpg' ]); $data = []; if($request->hasfile('filenames')) { // 用$request->file()读取上传文件 foreach($request->file('filenames') as $image) { $imagename= time() . '_' . $image->getClientOriginalName(); $image->storeAs('public/product_images', $imagename); $data[] = $imagename; } } $image= new Image(); // 直接从请求中获取表单传入的product_id赋值 $image->product_id = $request->product_id; $image->imagenames= json_encode($data); $image->save(); return back()->with('success', 'Your images were successfully uploaded!'); }
可选优化:单图对应单条记录
如果你的业务逻辑是每张图片对应一条image表记录,只需要把实例化Image的逻辑放到循环内部即可:
if($request->hasfile('filenames')) { foreach($request->file('filenames') as $image) { $imagename= time() . '_' . $image->getClientOriginalName(); $image->storeAs('public/product_images', $imagename); Image::create([ 'product_id' => $request->product_id, 'imagenames' => $imagename ]); } }
使用create方法前需要先在Image模型的$fillable属性中添加product_id和imagenames允许批量赋值。
内容的提问来源于stack exchange,提问作者Footy Flicks
相关产品推荐
相关产品推荐

