I'm sending my requests to the server using ajax and somehow at times, I may get TokenMismatchException on the server. Now, I want to handle this both on the backend as well as frontend. For this, I used a reference from this StackOverflow link:
public function render($request , Exception $exception)
{
//TODO Check the following if() block code validity for production server
if ($exception instanceof \Illuminate\Session\TokenMismatchException){
if ($request->expectsJson() ){
return Response::json([
'message' => 'Token mismatch (CSRF token mismatched)' ,
'message-type' => 'danger' ,
'new_csrf_token' => csrf_token()
], $exception->getStatusCode());
}
return redirect()
->back()
->exceptInput('password')
->with([
'message' => 'Validation Token was expired. Please try again' ,
'message-type' => 'danger' ,
]);
}
return parent::render($request , $exception);
}
Using this JSON response, I want to display a prompt message on the front end as well as update the CSRF token to resend the request.
But I get an error saying:
Call to undefined method Illuminate\Session\TokenMismatchException::getStatusCode()
Any ideas how can I manage to handle this exception for ajax request?
Laravel token miss match exception code is 419, you can use directly 419 instead of $exception->getStatusCode()