通过AJAX进行Laravel验证响应

时间:2017-07-31 14:49:04

标签: php ajax laravel-5.4

我正在使用Laravel 5.4身份验证过程实现基于AJAX的登录。

我一直收到422个回复,所以经过一些研究后,我在LoginController中提出了这个验证方法(它覆盖了AuthenticatesUsers特征方法:

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
        );

    }
}

我期待这样的回应:

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"
  ]
]

但我得到了这个回复

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

如果我在回复之前dd($messageBag),那么我会得到预期的结果。我错过了什么?

1 个答案:

答案 0 :(得分:1)

如果查看LoginController:login的方法定义,则不会返回$this->validateLogin,也不应返回。{/ p>

$this->validate抛出异常,当请求验证失败时,会针对AJAX和正常请求进行相应处理。

您应该将验证写为:

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',
    ]);
}

}