laravel: 如何将上传文件的路径存储在数据库中
laravel: 如何将上传文件的路径存储在数据库中
以下是我的控制器代码:
public function save(Request $request) { try { $this->validate($request, Country::rules()); 如果(Input::hasFile('flag_image')){ $file = Input::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; } $request['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', "无法保存国家数据.!!")->withInput(); } } catch (\Exception $ex) { return back()->with('error', "无法保存国家数据.!!")->withInput(); } }
当我在saveOrUpdate
函数之前使用dd($request)
时,我得到了上传文件的完整路径。
+request: ParameterBag {#40 ▼ #parameters: array:6 [▼ "_token" => "c94UG3R2PbbdHsXRLzs9OjEBTna23OHINFpki63U" "id" => "" "title" => "INDIA" "short_name" => "IN" "status" => "Active" "flag_image" => "public/images/admin/country/1515577652banner5.jpg" ]}
成功添加数据到表后,flag_image路径看起来像"D:\xampp\tmp\php63D3.tmp"
,我想存储"public/images/admin/country/1515577652banner5.jpg"
这个路径。
问题原因:在代码中,先调用了saveOrUpdate()方法更新了数据,然后又调用了save()方法创建了另一个查询来更新flag_image字段,导致表格被更新了两次。
解决方法:可以通过在请求中添加$request->except('flag_image')来避免这个问题。另外,可以使用Country::saveOrUpdate(array_merge($request->except('flag_image'), 'flag_image', $imgpath))来将请求的数组与flag_image路径合并。
需要注意的是,根据实际情况选择使用BM2ilabs的代码还是我的代码,并在选择后选择对应的答案。如果选择使用BM2ilabs的答案,需要重写saveOrUpdate()方法,因为在其中使用了$request对象,而except()方法会返回一个数组。
完整代码如下:
$country->flag_image = $imgpath; $country->save(); $country = Country::saveOrUpdate($request); // 选择以下其中一个代码 // 代码一 $country = Country::saveOrUpdate(array_merge($request->except('flag_image'), 'flag_image', $imgpath)); // 代码二 $country = Country::saveOrUpdate($request->except('flag_image')); $country->flag_image = $imgpath; $country->save();
选择最佳答案需要根据实际情况来决定,如果选择使用BM2ilabs的代码,需要勾选他的答案。如果选择使用我的代码,需要勾选我的答案。