Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Tikay's avatar
Level 1

Auth : How do I ajax user login/registry?

Hi,

Been trying to find a solution online, but they refer to controllers that don't exist where they say they do, dating back to Laravel 5.4 sadly.

Upon login/register form submit, I'd like to do a json response with fitting errors or update,

  $("#login-ajax").submit(function (e) {
    e.preventDefault();

    $.ajax({
        type: $(this).attr('method'),
        url: $(this).attr('action'),
        data: $(this).serialize(),
        headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') },
        success: function (data) {
          console.log('success');
        },
        error: function (data) {
          console.log('error');
        },
        complete: function() {

        }
    });
  });

Above works, logs "success" or "error" whether the user succeeded to log in or not, but I'd love to get a json response from Laravel back with a bunch of data.

Where's the file located where I can do adjustments for this to happen?

Thanks for your time as always! Hopefully my question was clear enough, been a long day..

0 likes
5 replies
jlrdw's avatar

You add the responses you want.

return Response::json(['success' => 'all okay']);

Put your custom response there.

2 likes
Tikay's avatar
Level 1

Thanks for the quick reply

My issue is more so that I am unable to find the function/file that handles it, or how to move it under app/Http/Controllers.

      protected function authenticate(Request $request)
      {
          return back()->withErrors([
              'email' => 'The provided credentials do not match our records.',
          ]);
          
          $credentials = $request->validate([
              'email' => ['required', 'email'],
              'password' => ['required'],
          ]);

          if (Auth::attempt($credentials)) {
              $request->session()->regenerate();

              return redirect()->intended('dashboard');
          }

          return back()->withErrors([
              'email' => 'The provided credentials do not match our records.',
          ]);
      }

I've added the above to the LoginController, an instant "return back" with errors, but it doesn't get called, it still does the usual redirect etc.

dennisprudlo's avatar

Is that the method where the route points to? What is your route definition In your routes/web.php file?

Tikay's avatar
Tikay
OP
Best Answer
Level 1

With laravel/ui it's set as Auth::routes();

      protected function authenticated(Request $request, $user) {
        if ($request->expectsJson()) {
          return response()->json(['success' => $user->name]);
        }
        else {
          return redirect()->route('backend.products.favorites');
        }
      }

      protected function sendFailedLoginResponse(Request $request){
        if ($request->expectsJson()) {
          return response()->json(['failed' => trans('auth.failed')]);
        }
        else {
          throw ValidationException::withMessages([
             $this->username() => [trans('auth.failed')],
          ]);
        }
      }

Just found that adding this to the LoginController sends back user's name when ajax'd and successful, and failed msg when failed.

Not too sure why the protected function authenticate(Request $request) mentioned above, copied from documentation, doesn't work.

jlrdw's avatar

Have you published fortify so you have control.

2 likes

Please or to participate in this conversation.