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

MarkMatute's avatar

Laravel Login with AJAX

How can i properly integrate an ajax login with Laravel? Can i use AngularJS for this?

0 likes
12 replies
mattkomarnicki's avatar

It's easy. Re-use your existing POST route for $.ajax and inside your authenticate method check request type. If you will detect ajax post request then simply as a response return a json with either true or false + any additional data you need.

2 likes
mattkomarnicki's avatar

@MarkMatute:

public function postLogin(Request $request)
{
    $auth = false;
    $credentials = $request->only('email', 'password');

    if (Auth::attempt($credentials, $request->has('remember'))) {
        $auth = true; // Success
    }

    if ($request->ajax()) {
        return response()->json([
            'auth' => $auth,
            'intended' => URL::previous()
        ]);
    } else {
        return redirect()->intended(URL::route('dashboard'));
    }
    return redirect(URL::route('login_page'));
}
6 likes
MarkMatute's avatar

@slick i cant send my ajax request, im getting errors, POST http://localhost:8000/auth/auth/login 500 (Internal Server Error) and this is my code ''' $(document).ready(function(){

var loginForm = $("#loginForm");
loginForm.submit(function(e){
    e.preventDefault();
    var formData = loginForm.serialize();

    $.ajax({
        url:'auth/login',
        type:'POST',
        data:formData,
        success:function(data){
            console.log(data);
        },
        error: function (data) {
            console.log(data);
        }
    });
});

alert('Successfully Loaded');

});

'''

skliche's avatar
skliche
Best Answer
Level 42

@MarkMatute Do you get any error or exception details in the ajax response, anything in your log files? HTTP 500 means that something on your server side went wrong.

1 like
spekkie2002's avatar

You can check your log files under the storrage/logs folder... Probably your 500 error can be resolved there :-)

Good luck

jlrdw's avatar

Ajax shouldn't be used for login, I never even send any secure information through ajax.

cimrie's avatar

I would disagree about not using AJAX - while I haven't used it myself, it should behave (or you can make it behave) exactly like a POST request from a form - especially if you also make sure CSFR protection is in place - and so its just a nice UX addition. Stripe effectively use AJAX for sending card details across the wire, so I wouldn't worry. If you're ever worried about security just slap an SSL (even if it is self-signed) on the page and all AJAX & form requests will be secured through that.

2 likes
igor_talevski's avatar

Some times browsers send OPTIONS request... you will need to handle csrf protection and origin (if you work on different domains). I have implemented AngularJS as GUI and Laravel as API and work like a charm... but, yes... for production please user SSL

jartaud's avatar

L5.1 will redirect after successfull login. So in case you want to prevent this behaviour, you'll have to override handleUserWasAuthenticated method from AuthenticatesUsers trait.

`` protected function handleUserWasAuthenticated(Request $request, $throttles) { if ($throttles) { $this ->clearLoginAttempts($request); }

    if (method_exists($this, 'authenticated')) {
        return $this ->authenticated($request, Auth::user());
    }
    if ($request->ajax()) {
           return response()->json([
               'intended' => \URL::previous()
           ]);
    } else {
        return redirect()->intended($this->redirectPath());
    }
}

`

4 likes
ahmed-aliraqi's avatar

Override this method in your LoginController to login by ajax :)

/**
 * The user has been authenticated.
 *
 * @param  \Illuminate\Http\Request  $request
 * @param  mixed  $user
 * @return mixed
 */
protected function authenticated(\Illuminate\Http\Request $request, $user)
{
    if ($request->ajax()){

        return response()->json([
            'auth' => auth()->check(),
            'user' => $user,
            'intended' => $this->redirectPath(),
        ]);

    }
}
8 likes
varuninorbit's avatar

@JLRDW - What difference Ajax makes in sending the secure information?

It is ok if it is sent to a https url.

Please or to participate in this conversation.