laravel 数组验证 - 计算数组的深度

问题描述 投票:0回答:1

我正在尝试验证可能具有任意数量级别的递归数据,例如

[
    'name' => 'test',
    'children' => [
        [
            'name' => 'test2'
        ],
        [
            'name' => 'test3',
            'children' => [
                'name' => 'test4'
            ]
        ],
        [
            'name' => 'test5',
            'children' => [
                'name' => 'test6'
                'children' => [
                    'name' => 'test7'
                ]
            ]
        ]
    ]
]

在此示例中,我需要以下规则来确保在每个级别指定名称:

$rules = [
    'name' => ['required'],
    'children' => ['array'],
    'children.*.name' => ['required'],
    'children.*.children' => ['array'],
    'children.*.children.*.name' => ['required'],
    'children.*.children.*.children' => ['array'],
    'children.*.children.*.children.*.name' => ['required'],
]

如何根据传入的数据动态生成验证规则?

laravel laravel-5
1个回答
0
投票
 public function save(array $attributes)
 {
    $errors = tap(new MessageBag(), fn($messageBag) => $this->validate($attributes, $messageBag));
    if ($errors->isNotEmpty()) {
        throw ValidationException::withMessages($errors->toArray());
    }
 }


/**
 * @param array       $attributes
 * @param IMessageBag $messageBag
 * @param string      $prefix
 * @return void
 */
protected function validate(array $attributes, IMessageBag $messageBag, string $prefix = ''): void
{
    $validator = Validator::make($attributes, [
        'ref'            => 'required',
        'parent_ref'     => 'nullable',
        'name'           => 'required',
        'original_name'  => 'required',
        'children'       => 'nullable|array',
    ]);

    if ($validator->fails()) {
        foreach ($validator->errors()->toArray() as $fieldName => $errors) {
            $messageBag->merge(["{$prefix}{$fieldName}" => $errors]);
        }
    }

    $children = $attributes['children'] ?? [];
    if (!empty($children)) {
        foreach ($children as $key => $child) {
            $this->validate($child, $messageBag, "{$prefix}children.{$key}.");
        }
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.