Home > front end >  validate nested array in laravel
validate nested array in laravel

Time:07-12

I have a SPA app (Vue 3 Laravel) and I have some problem with array validations....

The array (object from vue) that is send through API is this:

const groups = ref([
    {
        name: "Test Group 1",
        questions: [
            {name: "Test question 1 ?"},
            {name: "Test question 2 ?"}
        ],
        answers: [
            {
                type: "yn",
                values: [1, 0]
            },
            {
                type: "ny",
                values: [0, 1]
            }
        ]
    },
    {
        name: "Test Group 2",
        questions: [
            {name: "Test question 3 ?"},
            {name: "Test question 4 ?"}
        ],
        answers: [
            {
                type: "pt",
                values: [1, 0.5, 0]
            },
            {
                type: "pte",
                values: [1, 0.75, 0.5, 0.25, 0]
            }
        ]
   }
])

and in laravel I have created this rules for validations:

$request->validate([
    ...
    'content.*.answers' => 'required|array|min:1',
    'content.*.answers.*.type' => ['required', 'string', Rule::in('yn', 'ny', 'pt', 'pte')],
    'content.*.answers.*.values' => ['required', 'array', Rule::in([1, 0], [0, 1], [1, 0.5, 0], [1, 0.75, 0.5, 0])]
]);

it complains about the 'content..answers..values' that are not valid (for the values from second group):

Field content.1.answers.0.value selected is not valid. 
Field content.1.answers.1.value selected is not valid.

How can I validate and make sure the user send the right data?

In the object are all the possible answers...

If the type is "yn" the values should always be: [1, 0] and so on...

CodePudding user response:

Probably, i didn't try it yet, the Rule:in() that should match an array with an array of arrays doesn't work well... Try using a custom macro or a custom validator.

Look here for macros: macros

Pay attention to this array operators: php array operators

CodePudding user response:

You can try passing in custom validators as functions.

Refer to https://laravel.com/docs/9.x/validation#accessing-nested-array-data for more details

  • Related