Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Merged
merged 2 commits into from
Apr 21, 2020

Conversation

sileence
Copy link
Contributor

@sileence sileence commented Apr 19, 2020

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' => '[email protected]',
            '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" => "[email protected]"
      "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