4

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 2

8

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

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

Comments

0

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

2 Comments

Thanks for the reply. I thought about that but would love it if there was a more encapsulated way of doing it.
You could try conditional sometimes rule, but I never tried with the array keys and haven't seen any encapsulating approach for this sort of scenario.

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.