-1

I'm really confused about why this is happening? I had successfully added a record then when I tried to update the record It says that the field is required even I passing it already. Then when I tried to add "sometimes" on the validation. Now, it works. Why? Please enlighten me. Thank you!

my Test Model

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

3 Answers3

1

As per the doc sometimes is used for :

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', ]);

Therefore since the request is not containing the expected fields, the validation is successful

Christophe Hubert
  • 2,833
  • 1
  • 12
  • 25
1

Adding sometimes effectively disables the required rule and allows the client to simply not pass that field into the input.

In your case, the validator is probably not receiving the correct data from input. Because If it did, the required rule would act correctly.

Please post the code of your validator to be able to debug the problem.

HosseyNJF
  • 491
  • 1
  • 6
  • 18
0

sometimes is when you sometimes include the field.

Let's see an example of validation when creating a user:-

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

Sample payloads

{
 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
daisura99
  • 1,030
  • 1
  • 12
  • 22