問題描述
我正在處理一個表單,用戶可以在其中更新他們的出生日期.該表單為用戶提供了 3 個單獨的字段,分別為 day
、month
和 year
.在服務器端,我當然想將這 3 個單獨的字段視為一個值,即 yyyy-mm-dd
.
I'm processing a form where a user can update their date of birth. The form gives the user 3 separate fields for day
, month
and year
. On the server-side of course I want to treat these 3 separate fields as one value i.e. yyyy-mm-dd
.
所以在驗證和更新我的數據庫之前,我想通過連接 year
、month
和day
使用 -
字符創建我需要的日期格式(并且可能取消設置原始 3 個字段).
So before validation and updating my database, I want to alter the form request to create a date_of_birth
field by concatenating year
, month
and day
with -
characters to create the date format I need (And possibly unset the original 3 fields).
用我的控制器手動實現這一點不是問題.我可以簡單地獲取輸入,將由 -
字符分隔的字段連接在一起并取消設置它們.然后,我可以在傳遞給處理處理的命令之前手動驗證.
Achieving this manually with my controller is not a problem. I can simply grab the input, join the fields together separated by -
characters and unset them. I can then validate manually before passing off to a command to deal with the processing.
但是,我更喜歡使用 FormRequest
來處理驗證并將其注入到我的控制器方法中.因此,我需要一種在執行驗證之前實際修改表單請求的方法.
However, I would prefer to use a FormRequest
to deal with the validation and have that injected into my controller method. Therefore I need a way of actually modifying the form request before validation is executed.
我確實發現了以下類似的問題:Laravel 5 請求 - 更改數據
I did find the following question which is similar: Laravel 5 Request - altering data
它建議覆蓋表單請求上的 all
方法,以包含在驗證之前操作數據的邏輯.
It suggests overriding the all
method on the form request to contain the logic for manipulating the data prior to validation.
<?php namespace AppHttpRequests;
class UpdateSettingsRequest extends Request {
public function authorize()
{
return true;
}
public function rules()
{
return [];
}
public function all()
{
$data = parent::all();
$data['date_of_birth'] = 'test';
return $data;
}
這對驗證來說一切都很好,但是覆蓋 all
方法實際上并沒有修改表單請求對象上的數據.所以在執行命令時,表單請求包含原始未修改的數據.除非我使用現在覆蓋的 all
方法來提取數據.
This is all well and good for the validation, but overriding the all
method doesn't actually modify the data on the form request object. So when it comes to executing the command, the form request contains the original unmodified data. Unless I use the now overridden all
method to pull the data out.
我正在尋找一種更具體的方法來修改表單請求中的數據,而無需調用特定方法.
I'm looking for a more concrete way to modify the data within my form request that doesn't require the calling of a specific method.
干杯
推薦答案
在 laravel 5.1 中你可以做到
in laravel 5.1 you can do that
<?php namespace AppHttpRequests;
class UpdateSettingsRequest extends Request {
public function authorize()
{
return true;
}
public function rules()
{
return [];
}
protected function getValidatorInstance()
{
$data = $this->all();
$data['date_of_birth'] = 'test';
$this->getInputSource()->replace($data);
/*modify data before send to validator*/
return parent::getValidatorInstance();
}
這篇關于Laravel 5 Form Request 數據預操作的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!