Laravel: TokenMismatchException error

A common cause for this error (assuming you’re correctly passing along the form token) is the form session expiring. This chunk of code will warn the user when the session is about to expire and enable them to extend it by making a simple get request.

Note: you’ll need to add a /keep_alive route which return ‘success’ (or any other value).


<div class="alert alert-warning" id="keepAliveDiv" style="display:none">
    This page will expire soon, <a href="#" onclick="keepAlive()">click here</a> to keep working
</div>


<script type="text/javascript">
    var redirectTimer = null;
    function startWarnSessionTimeout() {
        var oneMinute = 1000 * 60;
        var twoMinutes = oneMinute * 2;
        var twoHours = oneMinute * 120;
        setTimeout(function() {
            warnSessionExpring();
        }, (twoHours - twoMinutes));
    }

    function warnSessionExpring() {
        $("#keepAliveDiv").fadeIn();
        redirectTimer = setTimeout(function() {
            window.location = '{{ URL::to('/dashboard') }}';
        }, 1000 * 60);
    }

    function keepAlive() {
        clearTimeout(redirectTimer);
        $('#keepAliveDiv').fadeOut();
        $.get('{{ URL::to('/keep_alive') }}');
        startWarnSessionTimeout();
    }

    $(function() {
        startWarnSessionTimeout();
    });

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s