Laravel技术问题:如何将上传文件的正确路径存储到数据库
解决Laravel中存储图片路径为临时文件路径的问题
你遇到的核心问题是直接修改$request对象的数组元素并没有正确更新请求的输入数据,导致saveOrUpdate方法仍然读取了原始的临时文件信息。下面是具体的分析和解决方案:
问题根源
在Laravel中,Illuminate\Http\Request对象的输入数据是通过内部受保护的属性管理的,直接使用$request['flag_image'] = $imgpath这种数组赋值方式,无法正确更新请求的输入集合。后续的saveOrUpdate方法大概率还是从文件上传的临时数据中获取了路径,而非你设置的正确路径。
解决方案
改用Request对象提供的merge方法来更新请求参数,这是Laravel官方推荐的修改请求输入的方式,能确保后续方法获取到正确的路径值:
修改后的控制器代码
public function save(Request $request) { try { $this->validate($request, Country::rules()); $imgpath = null; if($request->hasFile('flag_image')){ $file = $request->file('flag_image'); $destinationPath = public_path(). '/images/admin/country/'; $filename = $file->getClientOriginalName(); $image = time().$filename; $file->move($destinationPath, $image); $imgpath = 'public/images/admin/country/'.$image; } // 使用merge方法更新请求参数,替代直接数组赋值 if($imgpath) { $request->merge(['flag_image' => $imgpath]); } $country = Country::saveOrUpdate($request); if($country !== false) { return redirect()->route('lists-country')->with('success', trans('Country data added successfully.!!')); } else { return back()->with('error', "Unable to save country data.!!")->withInput(); } } catch (\Exception $ex) { return back()->with('error', "Unable to save country data.!!")->withInput(); } }
额外验证点
同时请检查Country模型的saveOrUpdate方法,确保它是从请求的输入数据中获取flag_image字段,而不是从文件上传数据中读取:
// 正确的取值方式:从输入集合中获取路径 $flagImage = $request->input('flag_image'); // 错误的取值方式:会获取临时文件对象/路径 // $flagImage = $request->file('flag_image');
完成以上修改后,数据库就能正确存储你设置的图片路径了。
内容的提问来源于stack exchange,提问作者Javed
相关产品推荐
相关产品推荐

