Jamal Abdul Nasir Jamal Abdul Nasir - 1 year ago 133
PHP Question

Handling expired token in Laravel

What is the best way to handle expired tokens in laravel 5.

I mean I have a page and it has some links which perform ajax requests. They work fine when the page is loaded but when I wait for sometime then I get a TOKEN MISMATCH error.

Now, I have to refresh the page to make it work again. BUT, I don't want to refresh the page. I want some way to refresh the token or some other work around to make it fix.

I hope you got my point.

Answer Source

a work around for it, is to actually get the new token every certain time, otherwise you are defeating the purpose of the csrf token:

        <meta name="csrf_token" content="{{ csrf_token() }}">
        <script type="text/javascript">
            var csrfToken = $('[name="csrf_token"]').attr('content');

            setInterval(refreshToken, 3600000); // 1 hour 

            function refreshToken(){
                    csrfToken = data; // the new token

            setInterval(refreshToken, 3600000); // 1 hour 


In laravel routes

Route::get('refresh-csrf', function(){
    return csrf_token();

I apologize in case of any syntax errors, haven't used jquery for long time, but i guess you get the idea

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download