Handle TokenMismatchException in laravel 5

I need to handle TokenMismatchException in laravel 5 so that if the token does not match, a message will be displayed to the user instead of the TokenMismatchException error.

+7
exception exception-handling laravel laravel-5
source share
2 answers

You can create custom exception rendering in the class App\Exceptions\Handler (in the file /app/Exceptions/Handler.php ).

For example, to render another view, when for a TokenMismatchException error TokenMismatchException 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); } 
+20
source share

You will need to write a function to render the TokenMismatchException error. You will add this function to your App \ Exceptions \ Handler class (in the /app/Exceptions/Handler.php file) as follows:

 // 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'); } 
+6
source share

All Articles