项目作者: victorybiz

项目描述 :
Handling Laravel CsrfToken Expiration Exception
高级语言:
项目地址: git://github.com/victorybiz/Handling-Laravel-CsrfToken-Expiration-Exception.git


Handling Laravel CsrfToken Expiration Exception

In Laravel, when you submit a form with expired csrf token, an error with TokenMismatchException is thrown.

To handle this exception gracefully and redirect back to the form with an error message and form inputs,
look at your app/Exceptions/Handler.php, at the render($request, Exception $exception) method/function.

Refactor the render($request, Exception $exception) method/function with the codes below.

  1. public function render($request, Exception $exception)
  2. {
  3. // ------ Start here
  4. if ($exception instanceof \Illuminate\Session\TokenMismatchException)
  5. {
  6. return redirect()
  7. ->back()
  8. ->withInput($request->except('password', '_token'))
  9. ->with(['alert_danger' => 'Your session timed out. Please try again']);
  10. }
  11. // ------ Ends here
  12. return parent::render($request, $exception);
  13. }

If the exception thrown is a TokenMismatchException, this will handle the exception.
Ensure to use the old('field_name') helper function to repopulate your form and Session::get('alert_danger')
to get returned error message.

Happy coding!