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

lorvent's avatar

How to deal with TokenMismatchException

I am running a laravel based website and using bugsnag for bug tracking.

a lot of time i get bug with "Illuminate\Session\TokenMismatchException"

its because people opened login page long back and entered details now, but showing error page is pretty awkward, so how can i display a nice message instead of that?

Any help is appreciated, Thanks.

0 likes
10 replies
JarekTkaczyk's avatar

Be more specific about what you want to achieve, but guessing you're seeing debug stacktrace, which is obviously bad idea.

Read this http://laravel.com/docs/4.2/errors and turn debug off in your app/config/app.php config (or other depending on the environment setup)

lorvent's avatar

Hi, I have turned off debug but still user don't see any useful info.

usually it happens when user opens a page and submits data after too much time gap but i want to display a nice message to the user when that happens.

bashy's avatar

Catch the TokenMismatchException exception?

JarekTkaczyk's avatar

@lorvent in the docs' section I linked you will find exactly what you need - handling errors. Use this and handle TokenMismatchException the way you'd like the app to respond to the user, ie. show some view with helpful notice or whatever.

lorvent's avatar

My problem is...

If we redirect visitor to login page because of TokenMismatchException.... whenever i create a form without token or send ajax request.... page will be redirected to login page.

so how to fix it for both scenarios?

MarkRedeman's avatar
Level 10

You don't have to specifically redirect the user to the login page. You can use Redirect::back() for these kind of errors.

App::error(function(Illuminate\Session\TokenMismatchException $exception)
{
    return Redirect::back()->withInput()->with('error', 'Your session was expired');
});
1 like
bashy's avatar

Be careful with back() since it relies on referral header

1 like
sagyLaravel's avatar

Hi All

in \app\Exceptions\Handler.php

if($e instanceof TokenMismatchException){
            return redirect('auth/login');
        }

i am redirecting to auth/login but if ajax request is there then in shows login form in my console it is not redirecting properly please do suggest

2 likes
CODEheures's avatar

@sagyLaravel I use a variant for escape AJAX request.

in \app\Exceptions\Handler.php:

public function render($request, Exception $exception)
    {
        if(!$request->isXmlHttpRequest() && $exception instanceof TokenMismatchException){
            return redirect(route('login'))->with('status', 'session expired');
        }
        return parent::render($request, $exception);
    }
1 like

Please or to participate in this conversation.