comancsm
3 years ago

Laravel Full Page Caching

Posted 3 years ago by comancsm

Hello,

I am trying to implement page caching on certain routes, just like in the lesson here: https://laracasts.com/lessons/caching-essentials.

However, Laravel 5.2 doesn't support filters anymore, and i am forced to use middleware as seen below.

Before Middleware:

  public function handle($request, Closure $next)
    {
        $response = $next($request);
        $cache=new CacheController();
        $key=$cache->make_cache_key($request->fullUrl());

        if(\Cache::has($key)){
            
            return response(\Cache::get($key));
        }

        return $response;
    }

After Middleware:

public function terminate($request,Response $response){

        $cache=new CacheController();
        $key=$cache->make_cache_key($request->fullUrl());



        if (!\Cache::has($key)){
           
            \Cache::put($key,$response->getContent(),60);
        }
    }

The caching works in a way. The cached response is returned and the page rendered, but the execution of the following code isn't stopped.

The controller logic placed after the middleware still gets executed, so do the queries, even though the page is already rendered to the user.

Is there a way to stop the request from going forward?

I tried just putting "return Cache::get('$key')" but this just returns an error:

FatalThrowableError in StartSession.php line 172:
Type error: Argument 1 passed to Illuminate\Session\Middleware\StartSession::addCookieToResponse() must be an instance of Symfony\Component\HttpFoundation\Response, string given, called in /home/vagrant/Code/Watch/vendor/laravel/framework/src/Illuminate/Session/Middleware/StartSession.php on line 72

Thanks in advance!

Please sign in or create an account to participate in this conversation.