Validation of array type request parameters in Laravel
![PHP-7.2](https://img.shields.io/badge/PHP-7.2-brightgreen)![Laravel-6.x](https://img.shields.io/badge/Laravel-6.x-brightgreen)
A note about writing validation for request parameters that Laravel treats as an array type.
Implementation
In the ** Request Parameter ** of the example below, describe the array obtained when the request parameter is obtained by $ request-> all ()
.
In ** Validation **, write an array that represents the validation rule.
You can test whether validation is effective by executing Validator :: validate ($ data, $ rules)
with Tinker etc. for each variable $ data
and $ rules
.
Example 1. array with key omitted
- -Request Parameter
$ data = [
'article_ids' => [1, 23, 456],
]
- -Validation
$ rules = [
'article_ids' =>'required | array',
'article_ids. *'=>'int',
];;
Example 2. Array consisting of a key and value pair
- -Request Parameter
$ data = [
'ingredients' => [
'egg' => true,
'peanuts' => false,
'others' =>'water'
],,
];;
- -Validation
$ rules = [
'ingredients' =>' required | array',
'ingredients.egg' =>' required | boolean',
'ingredients.peanuts' =>' required | boolean',
'ingredients.others' =>'string',
];;
Example 3. Nested array
- -Request Parameter
$ data = [
'person' => [
['first_name' =>'Taro','last_name' =>'Tanaka'],
['first_name' =>'Hanako','last_name' =>'Yamada'],
],,
];;
- -Validation
$ rules = [
'person' =>' required | array',
'person. *. First_name' =>' required_with: person. *. Last_name | string',
'person. *. Last_name' =>' required_with: person. *. First_name | string',
];;