首页 > 解决方案 > Laravel如何仅在内部数组之间验证不同的规则

问题描述

'variants' => ['nullable', 'array'],
'variants.*.name' => ['required', 'string'],
'variants.*.options' => ['required', 'array', 'min:1'],
'variants.*.options.*.code' => ['required', 'string', 'distinct'],

我在上面有一个验证规则。我想要实现的是仅用于内部数组之间的值的不同,但不知何故我在输入时遇到了这样的错误

输入:

{
   variants: [
       {
           name: "outer array 1",
           options: [
               {
                  code: "A"
               },
               {
                  code: "B"
               }
           ]
       },
       {
           name: "outer array 2",
           options: [
               {
                  code: "A"
               },
           ]
       }
   ]
}

结果:

"error": {
        "variants.0.options.0.code": [
            "The variants.0.options.0.code field has a duplicate value."
        ],
        "variants.1.options.0.code": [
            "The variants.1.options.0.code field has a duplicate value."
        ]
    }

问题:有什么方法可以区分内部数组而不是每个数组?

标签: phplaravelvalidationdistinctrules

解决方案


使用自定义验证规则:

<?php

namespace App\Rules;

use Illuminate\Contracts\Validation\Rule;

class Distinct implements Rule
{
    protected string $message;
    protected string $strict = '';

    public function __construct(bool $strict)
    {
        $this->strict = $strict ? ':strict' : '';
    }

    /**
     * @param string $attribute
     * @param array $value
     * @return bool
     */
    public function passes($attribute, $value)
    {
        try {
            $validation = \Validator::make(['array' => $value], [
                'array.*' => ["distinct{$this->strict}"]
            ]);
            $this->message = 'The field has a duplicate value.';
            return !$validation->fails();
        } catch (\Exception $exception) {
            $this->message = "array error";
            return false;
        }
    }

    public function message()
    {
        return $this->message;
    }
}

推荐阅读