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

NameUnknown's avatar

Updating after session expiration to avoid Error 419

As a user keeps page open and session gets expired, when user tries to do something, he gets the 419 error, which is logical. Is there a way to automatically update CSRF token as it gets expired so that user wouldn't face the 419 error at all?

0 likes
9 replies
LaryAI's avatar
Level 58

You can use the refresh_token method provided by the Illuminate\Foundation\Http\Middleware\VerifyCsrfToken middleware. This method will generate a new CSRF token and store it in the session.

public function handle($request, Closure $next)
{
    if ($this->isReading($request) || $this->tokensMatch($request)) {
        return $this->addCookieToResponse($request, $next($request));
    }

    if ($request->session()->token() != $request->input('_token')) {
        $request->session()->refresh_token();
    }

    throw new TokenMismatchException;
}

You can also use the refresh_token method in your controller or routes to manually generate a new CSRF token.

public function update(Request $request)
{
    $request->session()->refresh_token();

    // Do something
}
NameUnknown's avatar

@LaryAI Unfortunately, it throws error "Method Illuminate\Session\Store::refresh_token does not exist". We run a Laravel 9.47.0 application. Should it be addressed in some other way?

NameUnknown's avatar

@Sinnbeck That's quite a duct tape approach (no offence). Does Laravel have any methods to deal with such case?

Sinnbeck's avatar
Sinnbeck
Best Answer
Level 102

@NameUnknown Sadly no. Laravel is a backend framework. The session is meant to expire but laravel has no way of updating the frontend when a token expires. You could perhaps increase the duration

1 like
NameUnknown's avatar

@johnDoe220 No, I don't want to rebuild or force/hack anything. Just asking if there Laravel has a tweak for such case.

Please or to participate in this conversation.