Codeware 

Catch TokenMismatchException thrown by VerifyCsrfToken in Laravel

If you are using Laravel 5, you must have come across something like this when a form wasn’t after a long period of time of opening the page.

 

This was meant to help with checking against CSRF but it can be really annoying seeing this. Most of your user/visitors don’t understand the gibberish written, and you can’t possibly tell them to always submit the forms on time. No, you just can’t. Neither should you assume that they will only be visiting your website/app at the time they are on the page.

Solution

Don’t disable the CSRF verification on your site. DON’T!

You can just simply catch this error and do something with it (well, not literarily).

Let me show you how you can catch the error and possible display the form again.

  1. Open app/Exceptions/Handler.php
  2. Find the render() method
  3. Add this piece of code to it

    if ($exception instanceof TokenMismatchException){
        //redirect to a form. Here is an example of how I handle mine
        return redirect($request->fullUrl())->with('flash-msg', 'Oops! Seems you didn\'t submit form for a longtime. Please try again.');
    }
  4. So your render method should now look like this

    /**
     * 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){
            //redirect to a form. Here is an example of how I handle mine
            return redirect($request->fullUrl())->with('flash-msg', 'Oops! Seems you didn\'t submit form for a longtime. Please try again.');
        }
        return parent::render($request, $exception);
    }

You can decide to do something else instead of redirecting to the original form.

That, my friend, is how to overcome the ugly TokenMismatchException in VerifyCsrfToken.php without compromising your site’s security.

Afolabi 'aphoe' Legunsen on FacebookAfolabi 'aphoe' Legunsen on GithubAfolabi 'aphoe' Legunsen on GoogleAfolabi 'aphoe' Legunsen on LinkedinAfolabi 'aphoe' Legunsen on TwitterAfolabi 'aphoe' Legunsen on Youtube
Afolabi 'aphoe' Legunsen
Software Project Lead at itquette solutions
I'm a geek who desires to communicate with humans.

If you understand what I wrote and are not a fellow geek, then I've succeeded at having normal human conversations.

Related posts

One Thought to “Catch TokenMismatchException thrown by VerifyCsrfToken in Laravel”

  1. LastBlanche

    I have noticed you don’t monetize your website, don’t waste your traffic, you can earn additional bucks every month
    because you’ve got high quality content. If you want to know how to make
    extra money, search for: Mertiso’s tips best adsense alternative

Leave a Comment

%d bloggers like this: