I am adding conditional validation to my Laravel 5.1 site. The actual validation is working but my logic never seems to work as expected.
I have on my form three check boxes, each on should provide a value of true
when checked. This works with no issue.
The issue is in my validation, as seen in the code below. The test always returns false
no matter if the boxes are checked or not. I have the code validator below.
$validator->sometimes('email', 'required|email|max:255|unique:members,email', function($request) {
return $request->input('email_newsletter') === 'true';
});
Update:
Below is the full output of var_dump($request->input('email_newsletter'));
with the email checkbox checked:
object(Illuminate\Support\Fluent)#205 (1) { ["attributes":protected]=> array(8) { ["_token"]=> string(40) "arWeDoYSBUPDh6TnD2CI7xPbg5xfG4lyiCFjh1ZF" ["name"]=> string(0) "" ["email"]=> string(0) "" ["phone"]=> string(0) "" ["email_newsletter"]=> string(4) "true" ["text_message"]=> string(5) "false" ["call_message"]=> string(5) "false" ["input"]=> string(16) "email_newsletter" } }
The argument passed to the Closure
for the validation is an Illuminate\Support\Fluent
object that contains the input, it is not the Illuminate\Http\Request
object. You just access the information directly as attributes, without calling any method:
$validator->sometimes('email', 'required|email|max:255|unique:members,email', function($input) {
return $input->email_newsletter === 'true';
});
Before, when you use the statement $request->input('email_newsletter')
, all this does is actually set the input
attribute on the object to 'email_newsletter'
, and then returns the Fluent
object, which is then used in your comparison. You can see this in the dump that you added, the last attribute in the array is ["input"]=> string(16) "email_newsletter"
.
You can read up in the documentation here. The red box at the end of the section notes the object passed into the closure.