This question already has an answer here:
-
Laravel catch TokenMismatchException
4 answers
I am getting issues with CSRF exceptions being thrown to the user. They happen for perfectly innocent reasons like if someone takes too long to fill out a form when they finally submit it the session has expired and the tokens don't match. Now obviously this is an error but it doesn't need to kill everything and throw an exception.
Is there a way to just get it to set a flash message instead and redirect back to the original page. I don't want to disable CSRF protection I just want the errors to be handled a bit more gracefully.
This is a bit of a pain, I usually add a method to the VerifyCsrfToken class to catch the TokenMismatchException (in the Middleware folder):
public function handle($request, Closure $next)
{
try
{
return parent::handle($request, $next);
}
catch(TokenMismatchException $e)
{
return redirect()->back()->withInput()->withErrors(['tokenMismatch' => 'Have you been away? Please try submitting the form again!']);
}
}
Although, you might want to tweak that depending on how you are handling errors in your app.
This can be handled in app/Handler.php
Change the render function from
public function render($request, Exception $e)
{
return parent::render($request, $e);
}
To this:
public function render($request, Exception $e)
{
if ($e instanceof \Illuminate\Session\TokenMismatchException){
return redirect($request->fullUrl())->with('error',"Sorry your session has expired please resubmit your request.");
}
return parent::render($request, $e);
}