简体   繁体   中英

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?

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. You can check before validation if field_2 is set and react if not. The next step is adding nullable as validation rule to field_2 , eg

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

There is no field_2 in the data for it to validate, so it couldn't return what isn't there.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM