Search code examples
laravellaravel-validation

Laravel validation for nested array request where if one of the integer is zero, the other should be more than zero


I need to validate a laravel request like in this accepted answer in this stack overflow question. However my request is a nested array. What my current code based on the answer:

    $rules = [
        'nested_array.*.variable_a' => [
            'integer',
            'between:0,1',
            function ($attribute, $value, $fail) use ($data) {
                if (!$value && !$request['variable_b']) {
                    $fail($attribute . ' is invalid.'); //you can customize the message here
                }
            }
        ],
        'nested_array.*.variable_b' => 'integer|between:0,1',
        'nested_array.*.order' => ['required', 'integer'],
    ];

I am unable to use !$request['variable_b'] nor !$request['nested_array.*.variable_b'] returning Undefined array key. Will need to change the between:0,1 rule later but the main concern is to validate nested array.

If you have a different way for my question, that would help too.


Solution

  • You can simply back the logic a bit

    $rules = [
            'nested_array.*.variable_a' =>  'integer|between:0,1',
            'nested_array.*.variable_b' => 'integer|between:0,1',
            'nested_array.*.order' => ['required', 'integer'],
            'nested_array.*' => [
                function ($attribute, $value, $fail) use ($data) {
                    if (!$value['variable_a'] && !$value['variable_b']) {
                        $fail($attribute . ' is invalid.'); //you can customize the message here
                    }
                }
            ],
        ];
    

    You can also add the existence of the variable in the condition too

    $rules = [
            'nested_array.*.variable_a' =>  'integer|between:0,1',
            'nested_array.*.variable_b' => 'integer|between:0,1',
            'nested_array.*.order' => ['required', 'integer'],
            'nested_array.*' => [
                function ($attribute, $value, $fail) use ($data) {
                    if ((!isset($value['variable_a']) || !$value['variable_a']) && (!isset($value['variable_b']) || !$value['variable_b'])) {
                        $fail($attribute . ' is invalid.'); //you can customize the message here
                    }
                }
            ],
        ];