2017-06-19 58 views
0

我正在嘗試修改一個Laravel Request對象使用merge來更新密鑰trial_end合併後Laravel得到更新的請求值

我使用下面的代碼做這個...

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" 

爲什麼它沒有返回更新值的

結果?

+0

我會檢查是否在你的'$ request-> all()'有一個字段值爲'「12/4/2018」'。有些東西可能會覆蓋你的'trial_end'值。我想你沒有向我們展示所有的代碼。 – lesssugar

+0

@lesssugar這是所有的代碼。整個'$ request-> all()'在轉儲中。 – Henry

回答

0

想通了。解決的辦法是改變

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

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

這工作,因爲input()增加在all()的數據getInputSource()->all()上做一個data_get之前,而get()只是在執行data_get輸入參數(預修改)。

新的代碼(由亞歷克斯提出的改變)

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" 

希望這有助於該遇到這個問題的任何人。

+0

此外,找到[this](https://stackoverflow.com/questions/30186169/laravel-request-input-or-get)感興趣 – Henry

0

問題不在於賦值,而是通過比較,這是我個人最好的方法來檢查請求中的值是否已設置。

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'); 
} 

問候

+0

這也不起作用。我不想添加'trial_end'字段,我只是試圖修改現有的值。 ''測試''是佔位符。 – Henry

+0

我修改了你的代碼,並使用了合併功能,這是你想要的嗎? – alexalejandroem

+0

不,這與我的代碼所做的相反。 – Henry