5

Let's say i have an object composed of property_a and property_b, and when submitted have to receive at least one of those two properties.
If the object were just one i could use the required_without validation rule as follow

return [
    'property_a' => ['required_without:property_b'],
    'property_b' => ['required_without:property_a'],
];

If my object were itself inside another one it would be easy using the dotted notation:

return [
    'parent_object.property_a' => ['required_without:parent_object.property_b'],
    'parent_object.property_b' => ['required_without:parent_object.property_a'],
];

But how can i use this validation rule with an array of object?

return [
    'array.*.property_a' => ['required_without:???.property_b'],
    'array.*.property_b' => ['required_without:???.property_a'],
];

Documentation for required_without don't explicit say nothing about my use case.
Is there a workaround?

1
  • Could you post an example of your payload? Commented Dec 9, 2019 at 15:58

1 Answer 1

7

In validation array works both for keys and values, so you can use * even in the rules.

So try this:

return [
    'array.*.property_a' => ['required_without:array.*.property_b'],
    'array.*.property_b' => ['required_without:array.*.property_a'],
];

Reference: https://laravel.com/docs/6.x/validation#validating-arrays

1
  • 1
    Thanks so much. Wasn't aware of this. Especially that the "*" references "the same" element internally while iterating.
    – Danaq
    Commented Feb 22, 2021 at 15:50

Not the answer you're looking for? Browse other questions tagged or ask your own question.