Laravel 5: Request validate multidimensional array

2020-07-05 11:05发布

问题:

I have forms that submit multidimensional arrays. Like:

slide[1][title]
slide[2][title]

Now I use a Request class to define my rules. How can I loop through all array items within this class. I tried:

public function rules()
{
    return [
        'id' => 'required',
        'slide' => 'array|min:1',
        'slide.*.title' => 'required|max:255',
        'slide.*.description' => 'required|max:255',
    ];
}

But it did not work.

回答1:

Disclaimer: This solution was posted in the question by Alexej. Since answers shouldn't be shared in the question body and the OP seems to be inactive, I repost his answer as a community wiki for future readers:

I've found the solution by getting the slide array and loop through it.

public function rules()
{
    $rules = [
        'id' => 'required',
        'slide' => 'array|min:1',
    ];
    foreach($this->request->get('slide') as $key => $val){
        $rules['slide.'.$key.'.title'] = 'required|max:255';
        $rules['slide.'.$key.'.description'] = 'required|max:255';
    }
    return $rules;
}


回答2:

There's no preconfigured validation rule for multidimensional arrays. The easist way is to do the array validation inside your controller.

The problem is when you use multidimensional array to store single values, then the logic is wrong and what you should fix is your logic, not the framework.

For instance, I saw lots of time sending the user credentials like $var['login']['pass'] and $var['login']['username'], which it could be translated easily to 2 different variables, which would make more sense.

In case you know what those values should be and you feel confident that the validation could be something generic for all different values, you can create a custom validator (read validation documentation of your laravel version).

Referring to your code I think multidimensional array is declared the same way as in your html slide[]['title']. It'll be beneficial to know how you are sending those parameters to the backend, to then be able to give you a clue about how to set up the validation.