Laravel catch TokenMismatchException
You can handle TokenMismatchException Exception in App\Exceptions\Handler.php
<?php namespace App\Exceptions;
use Exception;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Illuminate\Session\TokenMismatchException;
class Handler extends ExceptionHandler {
/**
* A list of the exception types that should not be reported.
*
* @var array
*/
protected $dontReport = [
'Symfony\Component\HttpKernel\Exception\HttpException'
];
/**
* Report or log an exception.
*
* This is a great spot to send exceptions to Sentry, Bugsnag, etc.
*
* @param \Exception $e
* @return void
*/
public function report(Exception $e)
{
return parent::report($e);
}
/**
* 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 TokenMismatchException){
// Redirect to a form. Here is an example of how I handle mine
return redirect($request->fullUrl())->with('csrf_error',"Oops! Seems you couldn't submit form for a long time. Please try again.");
}
return parent::render($request, $e);
}
}
Handle TokenMismatchException in laravel 5
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);
}
How to to handle token mismatch exception in laravel post ajax?
In your app/Exceptions/Handler.php
file
Add a handler for TokenMismatchException
in the render
method
public function render($request, Exception $exception)
{
if ($exception instanceof \Illuminate\Session\TokenMismatchException) {
if ($request->expectsJson()) {
return response()->json([
'error' => 'Token mismatch'
], $exception->getStatusCode());
};
}
return parent::render($request, $exception);
}
This will return an error json response. You can customize the error response to suit your needs.
TokenMisMatchException in Laravel 5.4
Laravel makes it easy to protect your application from cross-site request forgery (CSRF) attacks. Cross-site request forgeries are a type of malicious exploit whereby unauthorized commands are performed on behalf of an authenticated user.
Laravel automatically generates a CSRF "token" for each active user session managed by the application. This token is used to verify that the authenticated user is the one actually making the requests to the application.
Anytime you define a HTML form in your application, you should include a hidden CSRF token field in the form so that the CSRF protection middleware can validate the request. You may use the csrf_field helper to generate the token field:
<form method="POST" action="/profile">
{{ csrf_field() }}
...
</form>
Reference
Handle TokenMismatchException for ajax request
Laravel token miss match exception code is 419, you can use directly 419 instead of $exception->getStatusCode()
Laravel exception handler not trapping TokenMismatchException
Chances are it's crashing because the return is expecting a \Illuminate\Http\Response
from render()
/**
* Render an exception into an HTTP response.
*
* @param \Illuminate\Http\Request $request
* @param \Exception $exception
* @return \Illuminate\Http\Response
*/
public function render($request, Exception $exception)
{
if($exception instanceof TokenMismatchException)
return response()->json('Token mismatch');
return parent::render($request, $exception);
}
Remember to use the correct class for the Exception
use Illuminate\Session\TokenMismatchException;
Related Topics
Get Numbers from String with PHP
Scaling a Chat App - Short Polling VS. Long Polling (Ajax, PHP)
Does Utc Observe Daylight Saving Time
How to Check If a Request If Coming from the Same Server or Different Server
The Csrf Token Is Invalid. Please Try to Resubmit the Form
Soap-Error: Parsing Wsdl: Couldn't Load from <Url>
Calculate Skip Value for Given Record for Sorted Paging
PHP Simplexml: Insert Node at Certain Position
Class 'App\Http\Controllers\Admin\Auth' Not Found in Laravel 5
How Can One Run Multiple Versions of PHP 5.X on a Development Lamp Server
Having Problems While Try to Install Oauth with Pecl in Mamp on MAC Os Lion
How to Get Previous Month and Year Relative to Today, Using Strtotime and Date
How to Fetch Associative Array Grouped by the Values of a Specified Column with Pdo
Convert an Associative Array to a Simple Array of Its Values in PHP