Tuesday, October 24, 2017

laravel 5 - Properly handle TokenMismatchException

In laravel 5 , When the token is expired you could get the TokenMismatchException. So we can avoid the exception and redirect back to the page with some error notification messages is best for the users.

I searched around and could not find a 100% definitive solution to this. I was able to find this bit of code but it does not seem to make any difference: App\Exceptions\Handler.php

 
public function render($request, Exception $exception){ 
  if ($exception instanceof TokenMismatchException){ 
    return redirect(url()->previous())->with('alert-danger', 
"Oops! Seems you couldn't submit form for a long time. 
Please try again."); 
    }
    return parent::render($request, $exception); 
 }