Laravel 5.7. I have a form request validation for a model Foo
. The model has an optional field bar
, which must be an array. If it is present, it must contain two keys, bing
and bang
. But if the array is absent, obviously these two keys should not be validated.
This is what I have so far:
return [
'bar' => 'bail|array|size:2',
'bar.bing' => 'required|numeric',
'bar.bang' => 'required|numeric',
];
This works when I send a request with the bar
array present. But when I send a request without the bar
array, I still get the validation errors
The bar.bing field is required
The bar.bang field is required
How can I make them only required when bar
is present?
Try with this rules
return [
'bar' => 'nullable|bail|array|size:2',
'bar.bing' => 'required_with:bar|numeric',
'bar.bang' => 'required_with:bar|numeric',
]
Docs for required_with
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With