1

I am implementing AJAX based login using Laravel 5.4 authentication process.

I keep getting 422 responses, so after some research , I came up with this validation method in my LoginController (which overrides the AuthenticatesUsers trait method:

protected function validateLogin(Request $request)
{
    $validator = Validator::make($request->all(), [
        $this->username() => 'required|email|max:50|unique:users',
        'nickname' => 'required|max:30|min:6|unique:users',
        'password' => 'required|confirmed|min:6',
    ]);

    if ($validator->fails()) {

        $responseBag = $validator->getMessageBag()->toArray();
        $responseBag['type'] = ['error'];

        if($request->ajax()) {
            return response()->json($responseBag, 422);
        }

        $this->throwValidationException(
            $request, $validator
        );

    }
}

I am expecting this response:

array:3 [
  "nickname" => array:1 [
    0 => "The nickname field is required."
  ]
  "password" => array:1 [
    0 => "The password confirmation does not match."
  ]
  "type" => array:1 [
    0 => "error"
  ]
]

But I get this response

{email: "These credentials do not match our records."}

If I dd($messageBag) before the response, then I get the expected result. What am I missing?

1 Answer 1

1

If you look at the method definition for LoginController:login, $this->validateLogin isn't returned and should not be.

$this->validate throws an exception which is handled accordingly for AJAX and normal requests when request validation fails.

You should write your validation as:

protected function validateLogin(Request $request)
{
    $this->validate($request, [
        $this->username() => 'required|email|max:50|unique:users',
        'nickname' => 'required|max:30|min:6|unique:users',
        'password' => 'required|confirmed|min:6',
    ]);
}

}

Sign up to request clarification or add additional context in comments.

1 Comment

Hi, thanks for the reply. If I dd($request->ajax()) before the if statement it returns true. If I place the dd inside the if statement, it triggers, so it is getting to the return JSON statement. Also, I am using jQuery (V3, latest) to post with $.ajax function. This has worked in prev. Laravel versions OK.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.