LoginSignup
43
30

More than 5 years have passed since last update.

Laravelで配列の必須バリデーション

Last updated at Posted at 2018-10-25

Laravelで配列のバリデーションをかけるときに少し試行錯誤をしたので備忘録と、連想配列の記事はあるけど配列の記事はあんまり無いなーという印象だったので。

バージョン
- laravel/framework 5.5.43
- PHP 7.1

リクエスト例

post.json
{
        "id": 10
        "select_id":[1,2,3],
        "images":["bar","foo"],
}

値を確認する場合

値の型や形式を確認するときはシンプルに実装できる

HogeRequest.php
public function rules()
    {
        return [
            'id' => 'required|integer',
            'select_id.*' => 'integer',
            'images.*' => 'string',
        ];
    }

プロパティは必須かつ配列であり、配列の値の形式を確認したいとき

こちらは少し冗長になってしまうが、まずプロパティ自体にもかける必要がある。
例えば'select_id.*' => 'required|integer', だとrequiredが無視されるので注意。

HogeRequest.php
public function rules()
    {
        return [
            'id' => 'required|integer',
            'select_id' => 'required|array',
            'select_id.*' => 'integer',
            'images' => 'required|array',
            'images.*' => 'string',
        ];
    }
43
30
3

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
43
30