Skip to content
Advertisement

Laravel requesting route and checking if user is logged in via ajax

I’m using Laravel version 7.11.0 and this is the scenario

  1. User logs into his account
  2. User doesn’t do anything on the webpage for a while so his session expires
  3. The user hits a button on my webpage that sends a Post request via Ajax to a route that can only be used by authenticated users
  4. Laravel correctly blocks that request because the user is not logged in

If that happens I would like to redirect that user to the login page. I know Laravel can do that but it isn’t working when I’m using Ajax. So how can this be done when using Ajax ? Thanks in advance.

The Route definition:

Route::group(['middleware' => ['auth','throttle:20,1']], function() {

Route::post('/searchProduct','ProductController@searchProduct')->name('searchProduct');

}); 

The Ajax Request

$.ajaxSetup({
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            }
        });

        $.ajax({
            type: 'POST',
            url: '/searchProduct',
            data: {
                search_term: $(".search_term").val()
            },
            success: function (data) {
                console.log(data.msg);

            },

                error: function (data) {

                console.log(errors.message);

            }
        });

Advertisement

Answer

As user is logged out you will retrieve an error. Than if you can make another ajax call that will check if user is logged in:

// Laravel
return auth()->check()

If this request receives false then you can redirect him to login page

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement