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!
-
3Please don't use pictures for code, use formatted text – Christophe Hubert Apr 30 '20 at 16:42
3 Answers
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

- 2,833
- 1
- 12
- 25
-
Without seeing the validation logic, that's the best I can provide – Christophe Hubert Apr 30 '20 at 16:46
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.

- 491
- 1
- 6
- 18
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

- 1,030
- 1
- 12
- 22