【问题标题】:laravel | How to replace a field in form's request?拉拉维尔 |如何替换表单请求中的字段?
【发布时间】:2017-04-07 12:37:36
【问题描述】:

我正在使用 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

请帮忙

【问题讨论】:

  • 把它当成一个普通数组就行了:$request['imagePath'] = $name,不是吗?
  • @Jean-PhilippeMurray 也尝试过,但它仍然没有改变任何东西

标签: php laravel replace laravel-5.4


【解决方案1】:

我相信merge()是正确的方法,它将提供的数组与ParameterBag中的现有数组合并。

但是,您错误地访问了输入变量。尝试改用$request-&gt;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-&gt;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

【讨论】:

  • 它打印了正确的名字!!所以如果我这样做 $user = User::create($request->all()); imagePath 会在表中有新的值吗?
  • 是的,它将具有新值。 $request-&gt;input() 将返回所有输入,$request-&gt;all() 将返回所有输入和文件。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-12-08
  • 2017-08-07
  • 2018-05-29
  • 1970-01-01
  • 2019-06-29
  • 2017-09-21
  • 2021-03-11
相关资源
最近更新 更多