laravel |如何替换表单请求中的字段?

laravel | How to replace a field in form's request?

我正在使用 laravel 5.4,我正在尝试替换请求中的 imagePath 字段(重命名上传的图片)。

解释:

提交表单时,请求字段 (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

请帮忙

我相信 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_path: https://github.com/laravel/framework/blob/5.4/src/Illuminate/Foundation/helpers.php#L635