1

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’ => ‘’]

2 Answers 2

1

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, e.g.

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

Sign up to request clarification or add additional context in comments.

1 Comment

thank you, this is a valid answer as well but i selected the other answer since i have a lot of optional fields to deal with
0

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

1 Comment

thank you, second option is the closest to what i need

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.