Search code examples
phpauthenticationlaravel-5.3

Laravel 5.3 modify LoginController response


I want to modify response messages in Laravel 5.3 LoginController. As of now, when I try to login, it redirects me to login page with messages displayed at the top.

But instead of it, I want to use ajax notifications to display messages. How can I modify the logic for response in LoginController?

Sample code for ajax call I am currently using

$.ajax({
  data: data,
  url: 'http://mywebsite.com/login',
  success:function(response){
        console.log(response);
  }
});

P.S - I am a newbie to Laravel and this is my first app using the framework


Solution

  • One way would be to override sendLoginResponse() and sendFailedLoginResponse() methods from the AuthenticatesUsers trait so that you can check if the request is an ajax (or wants json).

    In you Auth/LoginController add:

    /**
     * Send the response after the user was authenticated.
     *
     * @param  \Illuminate\Http\Request $request
     * @return \Illuminate\Http\Response
     */
    protected function sendLoginResponse(Request $request)
    {
        $request->session()->regenerate();
    
        $this->clearLoginAttempts($request);
    
        if ($request->ajax() || $request->wantsJson()) {
            return response()->json([
                'user' => $this->guard()->user(),
            ]);
        }
    
        return $this->authenticated($request, $this->guard()->user())
            ?: redirect()->intended($this->redirectPath());
    }
    
    /**
     * Get the failed login response instance.
     *
     * @param \Illuminate\Http\Request $request
     * @return \Illuminate\Http\RedirectResponse
     */
    protected function sendFailedLoginResponse(Request $request)
    {
        if ($request->ajax() || $request->wantsJson()) {
            return response()->json([
                $this->username() => Lang::get('auth.failed'),
            ], 422);
        }
    
        return redirect()->back()
            ->withInput($request->only($this->username(), 'remember'))
            ->withErrors([
                $this->username() => Lang::get('auth.failed'),
            ]);
    }
    

    This should allow you to keep to same routes for your project.

    Also, if you add dataType: 'json' it should parse the response for you i.e.:

    $.ajax({
      data: data,
      url: 'http://mywebsite.com/login',
      dataType: 'json',
      method: 'post',
      success:function(response){
    
            console.log('success', response);
      },
      error: function () {
          console.log('error', response)
      }
    });
    

    Hope this help!