对 Laravel "sometimes" 验证工作感到困惑

Confused about Laravel "sometimes" validation works

我真的很困惑为什么会这样?我已经成功添加了一条记录,然后当我尝试更新记录时它说即使我已经通过了该字段也是必需的。然后当我尝试在验证中添加 "sometimes" 时。现在,它起作用了。为什么?请赐教。谢谢!

my Test Model

This was the result when I tried to remove "sometimes"

根据文档 sometimes 用于:

Validating When Present In some situations, you may wish to run validation checks against a field only if that field is present in the input array. To quickly accomplish this, add the sometimes rule to your rule list:

$v = Validator::make($data, [
    'email' => 'sometimes|required|email', ]);

因此,由于请求不包含预期的字段,因此验证成功

添加 sometimes 有效地禁用了 required 规则,并允许客户端简单地不将该字段传递到输入中。

在您的情况下,验证器可能没有从输入中接收到正确的数据。因为如果是这样,required 规则将正确执行。

请post验证器的代码以便能够调试问题。

sometimes 是您 有时 包含该字段的时候。

让我们看一个创建用户时的验证示例:-

$validation = [
 "name" => "required|string|",
 "email" => "required|email",
 "hobbies" => "sometimes|array"
];

有效负载示例

{
 name: "Bob",
 email: "bob@gmail.com"
}
// this will pass
{
 name: "Bob",
 email: "bob@gmail.com",
 hobbies: ["fishing", "swimming"]
}
// this would also pass
{
 name: "Bob",
 email: "bob@gmail.com",
 hobbies: "swimming"
}
// this would fail since it doesn't match "array" validation