How To Handle Token Mismatch Exception

- 1 answer

I opened a Laravel form and left it as it is for long time (5-6 hours) or hibernated my computer. After long time or after resuming from hibernate when I submit the form it shows a TokenMismatchException.

I don't have any _token field by my own. But a _token field is added by Laravel in every form. It looks like this:

<input name="_token" type="hidden" value="YLyMGdfLKZESo51SYUHLKAzC6MNRLOQc9D9e2RFq">

I understand there is some token expiry issue, but it is bad to show a client an error message like this.

Now, I want to redirect my application to the login page or home page if the token is expired, or show a custom error message instead of a Laravel Token Mismatch error.

Note: I don't want to increase token expire time.



All exceptions are handled by the App\Exceptions\Handler class

Taka a look at Laravel 5.1 errors#render-method you will find that you can create a custom Exeption render, check the following example for the TokenMismatchException error, that will redirect the user to index view with custom message :

public function render($request, Exception $e)
    if ($e instanceof \Illuminate\Session\TokenMismatchException) {
        return response()->view('index', ['message' => 'custom message'], 500);
    return parent::render($request, $e);

Hope this helps.