Sometimes we get the 419 session expired error. Simple ways to handle the TokenMismatchException , is we put it on Exception Handler (global):
- bootstrap/app.php (Laravel 11)
->withExceptions(function (Exceptions $exceptions) {
$exceptions->render(function (\Illuminate\Session\TokenMismatchException $e, Request $request) {
return redirect()->route('login')->withErrors(['username' => 'Your session expired. Please log in again.']);
});
})
- app/Exceptions/Handler.php (Laravel 10)
use Illuminate\Session\TokenMismatchException;
public function render($request, Throwable $exception)
{
if ($exception instanceof TokenMismatchException) {
return redirect()->route('login')->withErrors(['username' => 'Your session expired. Please log in again.']);
}
return parent::render($request, $exception);
}
And just refresh the page. We can also do custom handler per route group, Middleware, session lifetime, or refresh the CSRF token, but this is simple enough.
Need help building your app? I’m available for freelance web & Android development — raflizocky.netlify.app
☕ Support my writing: paypal.me/raflizocky · saweria.co/raflizocky
Top comments (0)