Laravel validate array element is required if array is present

Viewed 5189

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?

2 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

Here's what I tend to do in this sort of situations

public function rules(): array
{
    $rules = [
        // ...
    ];

    if ($this->bar) {
        $rules['bar'] = 'array|size:2';
        $rules['bar.bing'] = 'required|numeric';
        $rules['bar.bang'] = 'required|numeric';
    }

    return $rules;
}
Related