douniao7308
douniao7308
2018-03-08 09:54

如何重写使用AJAX的方法?

  • php
  • ajax

I have a trait which handle password restoring logic:

public function reset(Request $request)
{
    $this->validate($request, $this->rules(), $this->validationErrorMessages());

    $response = $this->broker()->reset(
        $this->credentials($request), function ($user, $password) {
            $this->resetPassword($user, $password);
        }
    );

    return $response == Password::PASSWORD_RESET
                ? $this->sendResetResponse($response)
                : $this->sendResetFailedResponse($request, $response);
}

protected function rules()
{
    return [
        'token' => 'required',
        'email' => 'required|email',
        'password' => 'required|confirmed|min:6',
    ];
}

protected function sendResetFailedResponse(Request $request, $response)
{
    return redirect()->back()
                ->withInput($request->only('email'))
                ->withErrors(['email' => trans($response)]);
}

I want to use it with AJAX calls. How should I rewrite sendResetFailedResponse()?
When I use this logic without AJAX and if validation fails on rules() I simply get an error response with 422 status code. But if validation fails while on checking token validity (reset()) - there are no errors with status code in return.
My AJAX is like

axios.post('/password/reset', {
                    //data to send
                })
                .then((response) => {
                    ...
                })
                .catch((error) => {
                    //I can catch errors which are returning from rules() fail
                    //I want to catch non-valid token error here too
                }); 

I tried to override

protected function sendResetFailedResponse(Request $request, $response)
{
    return response(['email' => trans($response)]);
}

but this code returns token error after AJAX .catch()

  • 点赞
  • 回答
  • 收藏
  • 复制链接分享

1条回答

为你推荐

换一换