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'])) {

    ...
Share:
30,018
dcolumbus
Author by

dcolumbus

Updated on July 25, 2022

Comments

  • dcolumbus
    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
    dcolumbus over 9 years
    Yes, but I need to know what failed within my controller, before getting to the view.
  • Lynx
    Lynx over 9 years
    Well 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
    dcolumbus over 9 years
    $errors->all() produces Call to a member function all() on a non-object
  • Lynx
    Lynx over 9 years
    Sorry, yeah that won't work because it's supposed to redirect back to your previous page anyways. I will update the answer.
  • Lynx
    Lynx over 9 years
    Check my answer you may just be able to var dump the results using var_dump($validation->errors()); die;
  • dcolumbus
    dcolumbus over 9 years
    Converted to json, it seems to return {"email_address":{"Unique":["users","email"]}}
  • im_brian_d
    im_brian_d over 9 years
    updated. You have to check against it by field, each field having its own array of rules.
  • dcolumbus
    dcolumbus over 9 years
    Almost, but it's still always returning false, even though I can see that it's true.
  • im_brian_d
    im_brian_d over 9 years
    Updated, the rule Unique is a key, so in_array didn't work :) so instead I used isset