Laravel阵列键验证

时间:2019-06-06 07:00:00

标签: laravel validation

我有自定义请求数据:

{
    "data": {
        "checkThisKeyForExists": [
            {
                "value": "Array key Validation"
            }
        ]
    }
}

此验证规则:

$rules = [
    'data' => ['required','array'],
    'data.*' => ['exists:table,id']
];

如何使用Laravel验证数组密钥?

3 个答案:

答案 0 :(得分:3)

也许对你有帮助

$rules = ([
        'name' => 'required|string',              //your field
        'children.*.name' => 'required|string',           //your 1st nested field
        'children.*.children.*.name => 'required|string'        //your 2nd nested field
    ]);

答案 1 :(得分:0)

我认为这就是您要寻找的东西

$rules = [
   'data.checkThisKeyForExists.value' => ['exists:table,id']
];

答案 2 :(得分:0)

正确的方法
这在 Laravel 开箱即用是不可能的,但您可以添加新的验证规则来验证数组键:

php artisan make:rule KeysIn

规则应大致如下:

class KeysIn implements Rule
{
    public function __construct(protected array $values)
    {
    }

    public function message(): string
    {
        return ':attribute contains invalid fields';
    }

    public function passes($attribute, $value): bool
    {
        // Swap keys with their values in our field list, so we
        // get ['foo' => 0, 'bar' => 1] instead of ['foo', 'bar']
        $allowedKeys = array_flip($this->values);

        // Compare the value's array *keys* with the flipped fields
        $unknownKeys = array_diff_key($value, $allowedKeys);

        // The validation only passes if there are no unknown keys
        return count($unknownKeys) === 0;
    }
}

您可以像这样使用此规则:

$rules = [
    'data' => ['required','array', new KeysIn(['foo', 'bar'])],
    'data.*' => ['exists:table,id']
];

快捷方式
如果你只需要这样做一次,你也可以用快速而肮脏的方式来做:

$rules = [
    'data' => [
        'required',
        'array',
        fn(attribute, $value, $fail) => count(array_diff_key($value, $array_flip([
            'foo',
            'bar'
        ]))) > 0 ? $fail("{$attribute} contains invalid fields") : null
    ],
    'data.*' => ['exists:table,id']
];