如何在 Laravel 验证中要求数组并防止获得意外的键

Posted

技术标签:

【中文标题】如何在 Laravel 验证中要求数组并防止获得意外的键【英文标题】:How to require array in Laravel validation and prevent getting unexpected keys 【发布时间】:2021-05-26 16:42:07 【问题描述】:

我想为 laravel 中的对象数组设置需要验证并使用以下规则:

[
    'translations.*.languageId' => ['required', 'numeric', Rule::in(Language::all()->pluck('id'))],
    'translations.*.data.title' => 'required|string',
]

但是当我发送没有translations 键的请求时,validate 函数不会为translation 键抛出 require 错误。

所以我也单独添加了translations 键。

[
    'translations' => ['required', 'array'],
    'translations.*.languageId' => ['required', 'numeric', Rule::in(Language::all()->pluck('id'))],
    'translations.*.data.title' => 'required|string',
]

但是如果发送了一个不应该在translations 数组中的额外密钥(如locale),那么它仍然可以在validate 函数的输出中看到。

如何防止这种意外结果?

【问题讨论】:

看看这里,它解决了你的问题吗? ***.com/questions/66114290/… @ZiaYamin 对不起。 【参考方案1】:

正如 taylorotwell 回答 my issue 并关闭它,validator 无法进行此过滤。

过滤数组以仅在验证后包含您真正想要的项目。

【讨论】:

以上是关于如何在 Laravel 验证中要求数组并防止获得意外的键的主要内容,如果未能解决你的问题,请参考以下文章