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

mspace's avatar

How to redirect to previous after using TokenMismatchException

I have inserted this code to my project but it redirects me to home page instead of previous page


if ($exception instanceof \Illuminate\Session\TokenMismatchException) {
            return redirect()->route('login');
 }

0 likes
6 replies
Nakov's avatar

@thedesignlog it is good if you close other discussion related to the same issue, where I gave you the code that you use :)

you could've asked the question there too.

So do you enter this closure for sure?

Try adding :

if ($exception instanceof \Illuminate\Session\TokenMismatchException) {

    dd('I am here');
    return redirect()->route('login');
 }

This will tell you if the code is executed at all.

And make sure that your home route is auth protected, meaning:

Route::get('/home', 'HomeController@index')->middleware('auth');
mspace's avatar

I've done that but the problem is after It redirects me to the login page and after I login, it redirects me to the home page but i want it to redirect me to the previous page i was on

Nakov's avatar

@thedesignlog ah, then use redirect()->intended()

or check out the correct usage of that. Or you might need to store the path somewhere or cache it, and use that one. Because it will use the Login redirect path otherwise.

Nakov's avatar

@thedesignlog when I think more about this, instead of redirecting to the login page in the Exception handler, redirect back which whould logout the user and then when you login it should show you the previous page instead. Try and let me know :)

mspace's avatar

I figured it out. i used this which will attempt to load my current page which i have set the auth middleware in it's controller so it redirects me to login page since the session has expired and then takes me back to my previous after I login. Might seem complicated but it works

        if ($request->is('cart/*')) {

            if ($exception instanceof \Illuminate\Session\TokenMismatchException) {
                return redirect()->route('cart');
            }
        } else {

            if ($exception instanceof \Illuminate\Session\TokenMismatchException) {
                return redirect()->route('login');
            }
        }
Nakov's avatar

@thedesignlog and to simplify that, just use this:

if ($exception instanceof \Illuminate\Session\TokenMismatchException) {
     return redirect()->route($request->is('cart/*') ? 'cart' : 'login');
}

Should work the same :)

Please or to participate in this conversation.