title: How to resolve "ErrorException in VerifyCsrfToken.php" in Laravel
body: <p>This is was my approach:</p>
  
  <p>I run the following <strong>PHP Artisan</strong> commands:</p>
  
  <pre><code>php artisan make:middleware AfterCacheMiddleware
  
  php artisan make:middleware BeforeCacheMiddleware
  </code></pre>
  
  <p>Then, I updated my newly created middlewares (<strong><code>AfterCacheMiddleware</code></strong> and <strong><code>BeforeCacheMiddleware</code></strong>) as shown below:</p>
  
  <p><strong><em>AfterCacheMiddleware</em></strong></p>
  
  <pre><code>class AfterCacheMiddleware  {
  
      /**
       * Handle an incoming request.
       *
       * @param  \Illuminate\Http\Request  $request
       * @param  \Closure  $next
       * @return mixed
       */
      public function handle($request, Closure $next)
      {
          $response = $next($request);
  
          $key = $this-&gt;keygen($request-&gt;url());
  
          if( ! Cache::has( $key ) ) Cache::put( $key, $response-&gt;getContent(), 1 );
  
          return $response;       
      }
  
      protected function keygen( $url )
      {
          return 'route_' . Str::slug( $url );
      }
  }
  </code></pre>
  
  <p><strong><em>BeforeCacheMiddleware</em></strong></p>
  
  <pre><code>namespace App\Http\Middleware;
  
  use Closure;
  use Cache;
  use Str;
  
  class BeforeCacheMiddleware {
  
      /**
       * Handle an incoming request.
       *
       * @param  \Illuminate\Http\Request  $request
       * @param  \Closure  $next
       * @return mixed
       */
      public function handle($request, Closure $next)
      {
          $key = $this-&gt;keygen($request-&gt;url());
  
          if( Cache::has( $key ) ) return Cache::get( $key );
  
          return $next($request);
      }
  
      protected function keygen( $url )
      {
          return 'route_' . Str::slug( $url );
      }
  }
  </code></pre>
  
  <p>Further, I've registered both middlewares in my <strong><code>app/Http/Kernel.php</code></strong></p>
  
  <pre><code>'App\Http\Middleware\AfterCacheMiddleware',
  'App\Http\Middleware\BeforeCacheMiddleware',
  
  'cacheafter' =&gt; 'App\Http\Middleware\AfterCacheMiddleware',
  'cachebefore' =&gt; 'App\Http\Middleware\BeforeCacheMiddleware',
  </code></pre>
  
  <p>Below is my route:</p>
  
  <pre><code>Route::get('middle', ['middleware' =&gt; 'cachebefore','cacheafter', function()
  {
      echo "success";
  }]);
  </code></pre>
  
  <p>On a first page load, everything is normal <em>(because the page does not get cached)</em>.</p>
  
  <p>On a subsequent access, I get this error: <strong><em><code>ErrorException in VerifyCsrfToken.php line 76: Trying to get property of non-object</code></em></strong>.</p>
  
  <p>I think the error originates from this line:</p>
  
  <p><strong><code>if( Cache::has( $key ) ) return Cache::get( $key );</code></strong></p>
  
  <p>but I can't figure it out.</p>