How to avoid TokenMismatchException on logout?

If you stay too long on one form or get away from your computer, and then go back to fill it in – you may get a TokenMismatchException, because the CSRF token won’t be the same. It kinda makes sense, but the problem I recently discovered that it does the same for logout (which is also a form). And that’s pretty silly, so how to avoid it?

Basically, if you do nothing on the page for a few hours and then click logout, you may see something like this:

token mismatch exception laravel

To avoid this, we may add exceptions for the URLs that we don’t want to have CSRF protection. There’s a special array for that – in app/Http/Middleware/VerifyCsrfToken.php:

class VerifyCsrfToken extends Middleware
{
    /**
     * The URIs that should be excluded from CSRF verification.
     *
     * @var array
     */
    protected $except = [
        //
    ];
}

So what we should do, is add logout into this array:

protected $except = [
    '/logout'
];

You can add more URLs here, if you wish, but be careful – CSRF protection is quite an important thing.

Like our articles?
Check out our Laravel online courses!

2 COMMENTS

  1. I am bringing some changes from a laravel 5.6 project into a laravel 5.4 project. Everything works fine, except whenever I logout, it gives me the same token mismatch error. When I implemented the above solution, the following error arises

    Syntax error or access violation: 1142 UPDATE command denied to user ‘abc’ for table ‘users’ (SQL: update `users` set `remember_token` = ash6l4k56hlh66b6xffs6saa46ss4sc64vbnooiu where `id` = 1)

LEAVE A REPLY

Please enter your comment!
Please enter your name here