php - Can you explain the difference betwen laravels' "sometimes" and "nullable" validator on an example?
Solution:
If you want a minimal example here it is:
$validator = Validator::make([
'a' => null
], [
'a' => 'sometimes|integer'
]);
dump($validator->passes()); // false
$validator = Validator::make([
'a' => null
], [
'a' => 'nullable|integer'
]);
dump($validator->passes()); // true
Some notes: There's a middleware included in your Kernel.php by default called ConvertEmptyStringsToNull which when commented out will make data coming as empty from forms to be basically treated as missing instead of null.
sometimes|integer is functionally identical to integer in this particular case because a can either be missing, or an integer if it's not missing.
In general sometimes is like a "guard", you apply the validation rules on the right side of the guard if the field is present but you do nothing when absent. Otherwise without sometimes the validation rules always run but all (except the required* rules) pass when the field is missing.
Answer
Solution:
Let's say your request contains: {name: 'value'}
I believe that:
sometimesmeans that thenamefields can be present or not in the request body. Means it'll pass validation even if there is nonamefield on the requestnullablemeans that the field must be present, but the field value can benull. But in this case, you have to provide thenamefield even with a null value.
Let's say you have form with a particular input that is displayed only depending on previous input values. So this field is not always available: you can use sometimes as its "normal" that the user won't always submit this field.
In the other hand, if the field is always displayed but not required: you'll allow null values, but not the fact that the field is missing in the body: as it may be a bot or anything else that changed your form: not correct.
Answer
Solution:
Yes there is. When u have the nullable validation rule that means that the field that it is associated with it can have a null value when it is sent making it optional but it will always be validated.
'test_field1' => 'nullable|integer'
On the other hand the sometimes validation rule applies all other validation rules associated with a field only when that field is sent via the request. For example :
'test_field1' => 'sometimes|integer'
This means that test_field1 will bi validated if it is an integer only when the request data has that field.
You can read more about the validation rules in the official laravel documentation : https://laravel.com/docs/8.x/validation#conditionally-adding-rules https://laravel.com/docs/8.x/validation#rule-nullable
Source