Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel validate array element is required if array is present

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?

like image 697
GluePear Avatar asked Oct 17 '25 10:10

GluePear


1 Answers

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

like image 108
Nerea Avatar answered Oct 20 '25 01:10

Nerea



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!