Reputation: 4539
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?
Upvotes: 1
Views: 299
Reputation: 38922
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',
]);
}
}
Upvotes: 1