-
Before I send a PR I would like to introduce and propse my idea here. I consider this feature as small but helpful 'quality of life' improvement with no backwards compatibility issues. ProblemIt is not possible to use Given an array/request like this (or even more nested): public function rules(): array
{
return [
"channels" => "required|array",
"channels.*.type" => "required|string|min:3",
"channels.*.value" => "required|string|distinct|min:3",
"channels.*.description" => "nullable|string|min:3|max:80",
];
} The $validator->sometimes('channels.*.value', 'email:rfc,dns', function($item) {
return $item->type === 'email';
}); SolutionI would not touch the existing /**
* Add conditions to a given nested field based on a Closure.
*
* @param string $parent
* @param string|array $attribute
* @param string|array $rules
* @param callable $callback
* @return $this
*/
function sometimesNested(string $parent, $attribute, $rules, callable $callback)
{
foreach ((array) $this->getValue($parent) as $index => $item) {
$payload = new Fluent($item);
if ($callback($payload)) {
foreach ((array) $attribute as $key) {
$this->addRules([$parent . '.' . $index . '.' . $key => $rules]);
}
}
}
return $this;
} How it works: Basically the functionality is pretty much the same as in UsageDevelopers would have a convinient way to access and flexible validate nested items in a public function withValidator(Validator $validator)
{
// validate field 'value' as email, if field 'type is email
$validator->sometimesNested('channels', 'value', 'email:rfc,dns', function ($item) {
return $item->type === 'email';
});
// validate field 'value' as url, if field 'type' IS NOT email
$validator->sometimesNested('channels', 'value', 'url', function ($item) {
return $item->type !== 'email';
});
} Please see this idea as proof of concept. Suggestions to make it even better most welcome. Keen to make a PR with tests and docs changes, if there is a chance to get this merged. |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments
-
I've created a draft: |
Beta Was this translation helpful? Give feedback.
-
Opened a PR got it: #38385 |
Beta Was this translation helpful? Give feedback.
Opened a PR got it: #38385