I need to handle TokenMismatchException
in laravel 5 such a way that if token does not match it will show some message to user instead of TokenMismatchException
error.
Asked
Active
Viewed 8,587 times
8

seenukarthi
- 8,241
- 10
- 47
- 68

Rohit Pavaskar
- 308
- 2
- 12
2 Answers
23
You can create a custom exception render in the App\Exceptions\Handler
class (in the /app/Exceptions/Handler.php
file).
For example, to render a different view when for the TokenMismatchException
error, you can change the render
method to something like this:
/**
* Render an exception into an HTTP response.
*
* @param \Illuminate\Http\Request $request
* @param \Exception $e
* @return \Illuminate\Http\Response
*/
public function render($request, Exception $e)
{
if ($e instanceof \Illuminate\Session\TokenMismatchException) {
return response()->view('errors.custom', [], 500);
}
return parent::render($request, $e);
}

Hieu Le
- 8,288
- 1
- 34
- 55
-
Hi Hiew. Just tried you method and unfortunately I still get a "TokenMismatchException in VerifyCsrfToken.php line 53" whenever I post a fake a csrf token/ – Timothy Sep 22 '15 at 13:57
-
Can you add `var_dump($e); die();` before the `if` statement to check whether the `rendered` method is called or not. – Hieu Le Sep 22 '15 at 15:16
-
Yes, now I get the dirty page dump of object(Illuminate\Session\TokenMismatchException)#274 ... – Timothy Sep 23 '15 at 03:38
-
Now I just fixed it by adding the namespace on that App\ExceptionsHandler.php class - `use Illuminate\Session\TokenMismatchException;` Thanks! – Timothy Sep 23 '15 at 03:44
-
1I just noticed my mistake was doing `if ($e instanceof TokenMismatchException){` instead of the full path to the exception class. – Timothy Sep 23 '15 at 03:48
-
Just what I was looking for. Thank you! – West55 May 19 '16 at 19:13
7
You will need to write a function to render the TokenMismatchException error. You will add that function to your App\Exceptions\Handler class (in the /app/Exceptions/Handler.php file) this way:
// make sure you reference the full path of the class:
use Illuminate\Session\TokenMismatchException;
class Handler extends ExceptionHandler {
protected $dontReport = [
HttpException::class,
ModelNotFoundException::class,
// opt from logging this error to your log files (optional)
TokenMismatchException::class,
];
public function render($request, Exception $e)
{
// Handle the exception...
// redirect back with form input except the _token (forcing a new token to be generated)
if ($e instanceof TokenMismatchException){
return redirect()->back()->withInput($request->except('_token'))
->withFlashDanger('You page session expired. Please try again');
}

Timothy
- 4,198
- 6
- 49
- 59
-
Thanks, this is working except that the instance must have full path: `if ($exception instanceof \Illuminate\Session\TokenMismatchException){` – Guillaume Nov 16 '16 at 09:04
-
-
Can we extend this behavior by resubmit the form with data after token refreshed? – Marwan Jul 07 '19 at 11:35