【问题标题】:Laravel get updated request value after mergeLaravel 合并后获取更新的请求值
【发布时间】:2017-11-21 21:10:29
【问题描述】:

我正在尝试使用 merge 修改 Laravel Request 对象以更新密钥 trial_end

我正在使用以下代码执行此操作...

if ($this->request->get('trial_end', '')) {
    $this->request->merge(array('trial_end' => 'test'));
}
dd($this->request->all(), $this->request->get('trial_end'));

我希望$this->request->get('trial_end')test,但事实并非如此。 $this->request->all() 返回了我的预期。

芯片转储结果

array:1 [
  "trial_end" => "test"
]
"12/4/2018" 

为什么没有返回更新的值?

【问题讨论】:

  • 我会检查您的$request->all() 中是否有一个值为"12/4/2018" 的字段。某些东西可能会覆盖您的 trial_end 值。我猜你没有向我们展示所有代码。
  • @lesssugar 这是所有代码。整个 $request->all() 都在 die dump 中。

标签: php laravel merge request


【解决方案1】:

想通了。解决办法是改变

$this->request->get('trial_end');

$this->request->input('trial_end');

这是可行的,因为input()all() 中的数据添加到getInputSource()->all(),然后对其执行data_get,而get() 仅对输入参数执行data_get(预修改)。

新代码(Alex 建议的更改)

if ($this->request->has('trial_end')) {
    $this->request->merge(['trial_end' => 'test']);
}
dd($this->request->all(), $this->request->input('trial_end'));

新结果

array:1 [
  "trial_end" => "test"
]
"test"

希望这对遇到此问题的任何其他人有所帮助。

【讨论】:

  • 另外,找到感兴趣的this
【解决方案2】:

问题不在于分配,而在于比较,这是我个人检查请求中的值是否已设置的最佳方法。

public function test(Request $request){

    if (!$request->has('trial_end')) { //this is what you have wrong
        $request->merge(array('trial_end' => 'test'));
    }
    return $request->get('trial_end');
}

问候

【讨论】:

  • 这也不起作用。我不想添加trial_end 字段,我只是想修改现有值。 'test' 是占位符。
  • 我修改了你的代码,并使用了合并功能,这是你想要的吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-04-15
  • 1970-01-01
  • 2022-01-20
  • 2018-10-24
  • 2021-03-29
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多