问题描述
我正在处理一个表单,用户可以在其中更新他们的出生日期.该表单为用户提供了 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 数据预操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!