Laravel Validation: check why validator failed
30,018
Check for a specific rule within the returned array of failed rules
if ($validator->fails()) {
$failedRules = $validator->failed();
if(isset($failedRules['email_address']['Unique'])) {
...
Author by
dcolumbus
Updated on July 25, 2022Comments
-
dcolumbus almost 2 years
If there a way to check whether or not the validator failed specifically because of the
unique
rule?$rules = array( 'email_address' => 'required|email|unique:users,email', 'postal_code' => 'required|alpha_num', ); $messages = array( 'required' => 'The :attribute field is required', 'email' => 'The :attribute field is required', 'alpha_num' => 'The :attribute field must only be letters and numbers (no spaces)' ); $validator = Validator::make(Input::all(), $rules, $messages); if ($validator->fails()) {
In laymans terms, I basically want to know: "did the validation fail because the email_address was not unique?"
-
dcolumbus over 9 yearsYes, but I need to know what failed within my controller, before getting to the view.
-
Lynx over 9 yearsWell in your controller you can use that same foreach and it will display in your controller. I edited my answer so you can see
-
dcolumbus over 9 years$errors->all() produces
Call to a member function all() on a non-object
-
Lynx over 9 yearsSorry, yeah that won't work because it's supposed to redirect back to your previous page anyways. I will update the answer.
-
Lynx over 9 yearsCheck my answer you may just be able to var dump the results using var_dump($validation->errors()); die;
-
dcolumbus over 9 yearsConverted to json, it seems to return
{"email_address":{"Unique":["users","email"]}}
-
im_brian_d over 9 yearsupdated. You have to check against it by field, each field having its own array of rules.
-
dcolumbus over 9 yearsAlmost, but it's still always returning false, even though I can see that it's true.
-
im_brian_d over 9 yearsUpdated, the rule
Unique
is a key, soin_array
didn't work :) so instead I usedisset