[英]Laravel validation: how to get optional fields in the validated result array?
i'm validating request with required and optional fields.我正在使用必填和可选字段验证请求。 When the request does not contain the optional field, it's skipped and not returned in the validated() function, how can i get the optional field with empty string value in the returned array?
当请求不包含可选字段时,它会被跳过并且不会在 valid() function 中返回,如何在返回的数组中获取具有空字符串值的可选字段?
input is [‘field_1’ => ‘test’]
$validator = Validator::make($request->all(), [
‘field_1’ => [‘required’],
‘field_2’ => [‘string’]
]);
dd($validator->validated());
current output is [‘field_1’ => ‘test’]
desire output [‘field_1’ => ‘test’, ‘field_2’ => ‘’]
I don't know what version of laravel you're using, but my answer is valid for several laravel versions.我不知道您使用的是哪个版本的 laravel,但我的回答对几个 laravel 版本有效。 You can check before validation if
field_2
is set and react if not.您可以在验证之前检查是否设置
field_2
,如果没有设置则做出反应。 The next step is adding nullable
as validation rule to field_2
, eg下一步是将
nullable
作为验证规则添加到field_2
,例如
if (!isset($request->field_2)) {
$request->merge(['field_2' => null]); // or even ['field_2' => '']
}
$validator = Validator::make($request->all(), [
'field_1' => ['required'],
'field_2' => ['nullable', 'string']
]);
More information: https://laravel.com/docs/5.7/validation#a-note-on-optional-fields更多信息: https://laravel.com/docs/5.7/validation#a-note-on-optional-fields
There is no field_2
in the data for it to validate, so it couldn't return what isn't there.数据中没有
field_2
可供它验证,因此它无法返回不存在的内容。
You could ask the Request for these fields though:您可以询问这些字段的请求:
$request->all(['field_1', 'field_2']);
Or assign your validation rules to an array then you can use the array keys from it:或者将您的验证规则分配给一个数组,然后您可以使用其中的数组键:
$rules = [
'field_1' => '...',
'field_2' => '...',
];
...
$vals = $request->all(array_keys($rules));
dd($vals);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.