Miko Mi
Miko Mi

Reputation: 91

How do I prevent the mismatch token error in laravel?

I started using Laravel and it's great. A lot of useful functionality etc. However I have a problem about the csrf_token. My session time is the default 120 minutes and let's say I log in, and the browser tab stays open without me doing anything for those 120 minutes and expires, meaning I have to log in again. When I do something on the page after those 120 minutes of inactivity, that requires the user to be authenticated, using the POST method, I get the mismatch token exception error. Now I need to solve this because it is indeed a possibility that the user will leave his browser tab open without doing anything. Does anyone know how to solve this?

Upvotes: 2

Views: 1896

Answers (3)

ahmad faraji
ahmad faraji

Reputation: 1

change ur php to alt ... I did and It works fine now

change PHP in cpanel for example : from ea-php74 to alt-php74

and u will never see this again

just try this and done :)

for beginners :

Cpanel --> MultiPHP Manager ---> from ea-php74 to alt-php74

Upvotes: 0

Treast
Treast

Reputation: 1105

In your app/Exceptions/Handle.php, replace the render function with this one :

public function render($request, Exception $e)
{
     if ($e instanceof \Illuminate\Session\TokenMismatchException) {
            return redirect()
            ->back()
            ->withInput($request->except('password', '_token'))
            ->withError('Validation token has expired. Please try again');
     }
    return parent::render($request, $e);
}

It will redirect to the same page with a new token.

Upvotes: 3

Himanshu Upadhyay
Himanshu Upadhyay

Reputation: 6565

@Miko Mi, Laravel CSRF token is the token generated in session of the code and stored to sync into browser's memory.(cookie) and when you post any form or do any action, it will pass that CSRF token with the request and if it is expired, then it will give this exception token mismatch.

What you should do is, take to login page, if session is expired, (i.e. more than 120 minutes in your case) so CSRD token will be renewed and there won't be any problem.

Upvotes: 0

Related Questions