Skip to content

[7.x] Allow developers to specify accepted keys in array rule - #32452

Merged
taylorotwell merged 2 commits into
laravel:7.xfrom
sileence:validates_array_with_keys
Apr 21, 2020
Merged

[7.x] Allow developers to specify accepted keys in array rule#32452
taylorotwell merged 2 commits into
laravel:7.xfrom
sileence:validates_array_with_keys

Conversation

@sileence

@sileence sileence commented Apr 19, 2020

Copy link
Copy Markdown
Contributor

I'm trying to come up with a solution for the problem @mnabialek mentioned here #32379:


I'm sending such data in test:

$response = $this->post('/validate', [
    'users' => [
        [
            'name' => 'Person 1',
            'email' => 'sample@example.com',
            'is_admin' => true,
        ]
    ],
    'anything' => 'else',
]);

And my controller method looks like this:

$validated = $this->validate(request(), [
    'users' => ['required', 'array'],
    'users.*' => ['required', 'array'],
    'users.*.name' => ['required', 'string'],
    'users.*.email' => ['required', 'email'],
]);

dd($validated); returns:

array:1 [
  "users" => array:1 [
    0 => array:3 [
      "name" => "Person 1"
      "email" => "sample@example.com"
      "is_admin" => true
    ]
  ]
]

Although is_admin flag shouldn't be there.


In cases like this the validation could be changed slightly, specifying the keys that are accepted in any given array:

$validated = $this->validate(request(), [
    'users' => ['required', 'array'],
    'users.*' => ['required', 'array:name,email'],
    'users.*.name' => ['required', 'string'],
    'users.*.email' => ['required', 'email'],
]);

In this case both keys happened to be required and therefore they have their own validated rules, but that is not always going to be the case.

I was also trying to limit the amount of data in the validated array when more nested rules are specified but that's turning out to be a bit more difficult and also a breaking change, so I'm sending this rule option in the meantime as a way to whitelist the accepted keys in associative arrays.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants