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

X-Mac's avatar
Level 1

Protected route

Good morning, in my app I'm using some ajax call for rendering the page.

  1. I have some protected route, the access is reserved to logged user. For example /myaccount...If a user try to access at this route, laravel automatically redirect to the login page.

I want replay this behavoir with ajax.

$.ajax({ headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') }, type: 'POST', url: 'addToCart', data: { code:code, }, success: function(response) { ......

the route addToCart is protected, but in this case the redirect to login page is not working. How can I do this?

How everything is clear.

0 likes
3 replies
LaryAI's avatar
LaryAI
AI
Best Answer
Level 58

To handle the redirect to the login page when accessing a protected route via AJAX, you can check the response status code in the AJAX success callback. If the status code is 401 (Unauthorized), you can redirect the user to the login page using JavaScript.

Here's an example:

$.ajax({
    headers: {
        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
    },
    type: 'POST',
    url: 'addToCart',
    data: {
        code: code,
    },
    success: function(response) {
        // Handle successful response
    },
    error: function(xhr, status, error) {
        if (xhr.status == 401) {
            // Redirect to login page
            window.location.href = '/login';
        } else {
            // Handle other errors
        }
    }
});

In this example, if the AJAX request returns a 401 status code, the user will be redirected to the login page. Otherwise, you can handle other errors as needed.

Snapey's avatar

make sure your route is in web.php so that it can use sessions

Please or to participate in this conversation.