LoginSignup
34
24

More than 3 years have passed since last update.

Laravel で array 型のリクエストパラメータのバリデーション

Last updated at Posted at 2020-09-06

PHP-7.2 Laravel-6.x

Laravel で array 型として扱われるようなリクエストパラメータのバリデーションの記述に関するメモです。

実装

下記の例の Request Parameter にはリクエストパラメータを $request->all() で取得したときに得られる array を記述します。
Validation にはとバリデーションルールを表す array を記述します。

それぞれの変数 $data$rules に対して Validator::validate($data, $rules) を Tinker 等で実行すればバリデーションが効いているか試すことができます。

例1. key を省略した array

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

例2. key と value の組で構成された array

  • 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',
];

例3. ネストした 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',
];

参考

34
24
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
34
24