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

jmagaro88's avatar

Occasional TokenMismatchException

Occasionally, I'm seeing a TokenMismatchException in my laravel.log file from my site visitors. I might see only one or two of these per day out of thousands of visitors, so it's not a major issue, but it's still annoying me! In my Exception Handler file, I've added a log to see what route is causing the error to get a little more information, but I'm finding that it's not always the same route that causes the error.

I am using the Laravel Collective Form facade to create every one of my forms in my views, so I do not have any forms with missing tokens. Since the occurrence is so rare, I'm thinking that some people are just spending too much idle time on a page without clicking anything and causing the session to expire. To prevent against this, I added the LaravelCaffeineDripMiddleware to my global middleware in App\Http\Kernel. This may have helped a bit, but just now, I checked my logs and saw yet another TokenMismatchException. I looked at the stack trace and saw that the request definitely passed through the Laravel Caffeine middleware, so that's definitely working.

As a stop-gap, I have set up a way to gracefully handle these TokenMismatchExceptions by redirecting back to the previous page with back()->exceptInput('_token') so that the token is refreshed and letting the visitor know that they should submit the form again. However, I would prefer to simply solve whatever is causing this occasional error.

Does anyone have any ideas on how I could trace down what might be causing this?

0 likes
1 reply
d3xt3r's avatar
  1. Idle sessions, load the form, go for a brunch, come back, fill it up and submit ... add a field to your form, the time it was created, when a mismatch occurs, within exception handler, get hold of request and the time parameter and check.

  2. Sporadic cases could be anything, user clearing cookies, submitting the form or just playing around ...

Please or to participate in this conversation.