Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationEventAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
2
Help us understand the problem. What is going on with this article?
@hamakou108

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

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

参考

2
Help us understand the problem. What is going on with this article?
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
2
Help us understand the problem. What is going on with this article?