【问题标题】:laravel : How to Store file uploaded path in databaselaravel:如何将文件上传的路径存储在数据库中
【发布时间】:2018-06-19 10:52:32
【问题描述】:

这是我的控制器代码:

 public function save(Request $request) {
    try {

        $this->validate($request, Country::rules());


        If(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', "Unable to save country data.!!")->withInput();
        }
    } catch (\Exception $ex) {
        return back()->with('error', "Unable to save country data.!!")->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" 这个路径。

【问题讨论】:

  • 尝试:$country = Country::saveOrUpdate($request->all()); 而不是 $country = Country::saveOrUpdate($request); 希望这会解决它!

标签: php database laravel storage


【解决方案1】:

做吧

$country->flag_image = $imgpath;
$country->save();

之后

$country = Country::saveOrUpdate($request);

【讨论】:

  • 工作thanx...但不明白会发生什么。?
  • @Javed 使用此代码,您将更新表两次。您的saveOrUpdate() 方法将更新数据,然后save() 将创建另一个查询来更新flag_image
  • 因为您在请求中注册了所有内容并且请求具有 flag_image 所以如果您想防止这种情况,只需添加 $request->except('flag_image') 以避免这种情况
  • @Alexey Mezenin 提到,如果您想避免将请求数组与 flag_image 路径合并,例如 Country::saveOrUpdate(array_merge($request->except('flag_image '), 'flag_image' , $imgpath) );
  • @Javed 您应该选择最佳答案。如果您使用 BM2ilabs 的代码,请勾选他的答案。如果您要使用我的代码,请勾选我的答案。
【解决方案2】:

你需要merge()它:

$request->merge(['flag_image' => $imgpath]);

代替:

$request['flag_image'] = $imgpath;

【讨论】:

  • 感谢分享这个。合并看起来更干净,我不知道这个,
猜你喜欢
  • 2016-10-03
  • 1970-01-01
  • 2018-10-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-07-25
  • 2021-01-02
相关资源
最近更新 更多