2017-04-07 27 views
0

我正在使用laravel 5.4,我试图替换我的请求中的imagePath字段(重命名上传的图像)。laravel |如何替换表单请求中的字段?

解释:

当表单提交请求场(request->imagePath)包含上传的图片的临时位置,我认为TMP图像移动到一个目录,而改变其名称($name)。所以现在作为request->imagePath仍然具有旧的tmp图像位置我想要更改request->imagePath值以具有新的位置,然后创建用户。

像这样

 if($request->hasFile('imagePath')) 
    { 
      $file = Input::file('imagePath'); 

      $name = $request->name. '-'.$request->mobile_no.'.'.$file->getClientOriginalExtension(); 

      echo $name."<br>"; 

      //tried this didn't work 
      //$request->imagePath = $name; 

      $file->move(public_path().'/images/collectors', $name); 

      $request->merge(array('imagePath' => $name)); 

      echo $request->imagePath."<br>"; 
    } 

但它不能正常工作,这里是输出

mahela-7829899075.jpg 

C:\xampp\tmp\php286A.tmp 

请帮助

+0

只需使用它作为一个规则阵列:'$请求[ '的ImagePath'] = $ name',没有? –

+0

@ Jean-PhilippeMurray也尝试过,但它仍然没有改变任何东西 –

回答

2

我相信merge()是正确的方法,它会与提供的数组合并现有阵列在ParameterBag

但是,您正在错误地访问输入变量。尝试使用$request->input('PARAMETER_NAME'),而不是...

因此,你的代码应该是这样的:

if ($request->hasFile('imagePath')) { 
    $file = Input::file('imagePath'); 
    $name = "{$request->input('name')}-{$request->input('mobile_no')}.{$file->getClientOriginalExtension()}"; 

    $file->move(public_path('/images/collectors'), $name); 
    $request->merge(['imagePath' => $name]); 

    echo $request->input('imagePath')."<br>"; 
} 

注意:您还可以通过你的路径进入public_path(),它会串连它。

参考
检索输入:
https://laravel.com/docs/5.4/requests#retrieving-input
$request->merge()https://github.com/laravel/framework/blob/5.4/src/Illuminate/Http/Request.php#L269
public_pathhttps://github.com/laravel/framework/blob/5.4/src/Illuminate/Foundation/helpers.php#L635

+0

它印上了正确的名字!所以如果我做$ user = User :: create($ request-> all()); imagePath会在表中有新的值吗? –

+0

是的,它会有新的价值。 '$ request-> input()'将返回所有输入,'$ request-> all()'将返回所有输入和文件。 – user1960364

+0

它工作!非常感谢!你保存了一天 –