This is was my approach:

I run the following **PHP Artisan** commands:

```
php artisan make:middleware AfterCacheMiddleware

php artisan make:middleware BeforeCacheMiddleware

```

Then, I updated my newly created middlewares (**`AfterCacheMiddleware`** and **`BeforeCacheMiddleware`**) as shown below:

***AfterCacheMiddleware***

```
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->keygen($request->url());

        if( ! Cache::has( $key ) ) Cache::put( $key, $response->getContent(), 1 );

        return $response;       
    }

    protected function keygen( $url )
    {
        return 'route_' . Str::slug( $url );
    }
}

```

***BeforeCacheMiddleware***

```
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->keygen($request->url());

        if( Cache::has( $key ) ) return Cache::get( $key );

        return $next($request);
    }

    protected function keygen( $url )
    {
        return 'route_' . Str::slug( $url );
    }
}

```

Further, I've registered both middlewares in my **`app/Http/Kernel.php`**

```
'App\Http\Middleware\AfterCacheMiddleware',
'App\Http\Middleware\BeforeCacheMiddleware',

'cacheafter' => 'App\Http\Middleware\AfterCacheMiddleware',
'cachebefore' => 'App\Http\Middleware\BeforeCacheMiddleware',

```

Below is my route:

```
Route::get('middle', ['middleware' => 'cachebefore','cacheafter', function()
{
    echo "success";
}]);

```

On a first page load, everything is normal *(because the page does not get cached)*.

On a subsequent access, I get this error: ***`ErrorException in VerifyCsrfToken.php line 76: Trying to get property of non-object`***.

I think the error originates from this line:

**`if( Cache::has( $key ) ) return Cache::get( $key );`**

but I can't figure it out.