2
votes

I'm using Laravel Form Request Validation to validate an array of objects, within each object we have two keys neverExpires and numberOfBillingCycles. Neither of these two keys are required, but if both have a value validation should fail as I only want to accept one or the other.

"addOns": {
    "add": [
        {
            "inheritedFromId": "EMEX1",
            "neverExpires": "false",
            "numberOfBillingCycles": "10"   
        },
        {
            "inheritedFromId": "EX1",
            "neverExpires": "true"
        },
        {
            "inheritedFromId": "EX2"
        }
    ]
},

So, in the first instance, because both neverExpires and numberOfBillingCycles have values it should fail validation. The second and third instances should pass as it only contains neverExpires or doesn't contain either.

I've tried creating a custom validator and passing in the two fields as parameters eg.addOns.add.*.neverExpires and addOns.add.*.numberOfBillingCycles but the problem is the parameter index is not set and I can't seem to find the array index within the custom rule to enable me to check the right array object values.

Hope this makes sense? Cheers in advance.

1
can you show us your store request file?JoseSilva
@JoseSilva I've torn it down now as couldn't get it to work at all sorry. I've tried all the require_without, require_if etc and they don't appear to allow me to only ensure one or the other is completed or allow none of them to be completed. I only want it to fail validation if both are present and have value.Phil Rowley
did you tried after validation? function withValidator() ?JoseSilva
What version of Laravel are you using?Rwd
@JoseSilva thanks for taking the time to reply but I went with Ross's solution as it did what I needed.Phil Rowley

1 Answers

3
votes

As long as you're using >= Laravel 5.5 you could validate the item in the add array rather than the individual attributes:

public function rules()
{
    return [
        'addOns.add.*' => [
            function ($attr, $value, $fail) {
                if (array_has($value, ['inheritedFromId', 'numberOfBillingCycles'])) {
                    $fail('You can not have both');
                }
            },
        ],
    ];
}