I have always found it frustrating that failing the CSRF check in Laravel 5.x throws an exception. I would rather prefer it redirect the user back to the previous page, and get them to try again. So, I modified the VerifyCsrfToken.php
middleware to do just that, in just a few lines of code.
In the VerifyCsrfToken.php
(found in folder App\Http\Middleware
), I added the handle function that overwrites the default Laravel behaviour when the CSRF check fails. If this file doesn’t exist in your installation, the full code is included below:
On lines 22-29, I make sure unit tests, successful CSRF checks and pages that are excluded work as they should (this was taken from the original Illuminate\Foundation\Http\Middleware\VerifyCsrfToken
class).
On line 32, instead of throwing the TokenMismatchException
exception, I use the Redirect
facade to redirect the user back to the previous page, and display an error.
Note: Remember to include the use
statement for both the Closure
and Redirect
facades (see lines 5-6), or you will get exceptions when running your code.
Next time the CSRF check fails, your users will get a better looking error message and the chance to retry. Here is an example of how it looks on the login page:
Nice one, Thank you! I wasn’t able to redirect from a TokenMismatchException, your script did the trick.
Thans for help in this question!
You have the error in your code.
Must be “withErrors”:
return Redirect::back()->withErrors(‘Sorry, we could not verify your request. Please try again.’);
Thanks for pointing that out. The correct code is actually:
return Redirect::back()->withErrors( ['Sorry, we could not verify your request. Please try again.'] );
public function handle($request, Closure $next)
{
if (
$this->isReading($request) ||
$this->runningUnitTests() ||
$this->inExceptArray($request) ||
$this->tokensMatch($request)
) {
return $this->addCookieToResponse($request, $next($request));
}
// redirect the user back to the last page and show error
return Redirect::back()->withErrors( trans('auth.token_failed') );
}
new code 2018