Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel sometimes vs sometimes|required

What is the difference between sometimes|required|email and sometimes|email in Laravel validation?I've read this discussion from laracasts but still it is ambiguous for me

like image 354
alex Avatar asked Mar 07 '16 08:03

alex


People also ask

What is sometimes in laravel?

sometimes: Only apply the rest of the validation rules if the field shows up in the request. nullable: If the field shows up in the request and is null (undefined, empty, has no value at all, etc), do not apply the rest of the validation rules.

What is nullable laravel validation?

Using the nullable rule, you are telling Laravel that the field under validation may be null but if it is not null, to validate it against the rest of rules in the array for that key.

What is bail in laravel validation?

The bail validation rule applies to a "multi-rule" attribute. It does not stop running validation for other attributes. From the documentation: $request->validate([ 'title' => 'bail|required|unique:posts|max:255', 'body' => 'required', ]);


1 Answers

From the docs:

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

https://laravel.com/docs/5.2/validation#conditionally-adding-rules

If I could simplify it, I would say sometimes means, only apply the rest of the validation rules if the field shows up in the request. Imagine sometimes is like an if statement that checks if the field is present in the request/input before applying any of the rules.

I use this rule when I have some javascript on a page that will disable a field, as when a field is disabled it won't show up in the request. If I simply said required|email the validator is always going to apply the rules whereas using the sometimes rule will only apply the validation if the field shows up in the request! Hope that makes sense.

Examples:

input: []
rules: ['email' => 'sometimes|required|email']
result: pass, the request is empty so sometimes won't apply any of the rules

input: ['email' => '']
rules: ['email' => 'sometimes|required|email']
result: fail, the field is present so the required rule fails!

input: []
rules: ['email' => 'required|email']
result: fail, the request is empty and we require the email field!
like image 70
haakym Avatar answered Oct 03 '22 05:10

haakym