Validation of array type request parameters in Laravel

Sep 6, 2020 PHP 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

$ data = [
    'article_ids' => [1, 23, 456],
]
$ rules = [
    'article_ids' =>'required | array',
    'article_ids. *'=>'int',
];;

Example 2. Array consisting of a key and value pair

$ data = [
    'ingredients' => [
        'egg' => true,
        'peanuts' => false,
        'others' =>'water'
    ],,
];;
$ rules = [
    'ingredients' =>' required | array',
    'ingredients.egg' =>' required | boolean',
    'ingredients.peanuts' =>' required | boolean',
    'ingredients.others' =>'string',
];;

Example 3. Nested array

$ data = [
    'person' => [
        ['first_name' =>'Taro','last_name' =>'Tanaka'],
        ['first_name' =>'Hanako','last_name' =>'Yamada'],
    ],,
];;
$ rules = [
    'person' =>' required | array',
    'person. *. First_name' =>' required_with: person. *. Last_name | string',
    'person. *. Last_name' =>' required_with: person. *. First_name | string',
];;

Reference