Caching Routes in Laravel 4 Utilizing Different Environments
Sep 16, 2013  

So I'm experimenting with the power and flexibility of Larvel 4. This "blog/site" for me is just a learning experience or proof of concept. With that being said, I rely on those who came before to bring me up to speed. Yes, I'm very corny.

Caching in Laravel can be done in many ways and on many levels of coding. Like for instance you can cache the results that Eloquent returns, to save the load on your database. You can also cache time consuming operations like retrieving data from an external source. These are examples where you cache the result set of your data source and it's a good practice when you want to create a blazing fast website. (Caching routes using filters in Laravel 4 by Mark van Eijk)

Mark has really done a top notch job on this article and I highly suggest you read it if you haven't already. I'm not even thinking that I can improve on the concept here, but I did want to customize it for my needs during development. So I'm not going to repost Mark's code or elaborate in to much detail, read his post.


Simply put, the objective is to cache routes using filters for production and process routes in the development environment. I also set a flag for debug for the rare instances where I use it in my production environment.

The Codes

Update 09/21/2013

I quickly discovered this didn't work with pagination and that's a problem since I wanted to use it on my index / tag routes. So, I modified the code just a bit and here is our new result.

Route::filter('cache', function($route, $request, $response = null)
    $page = (Paginator::getCurrentPage() > 1 ? Paginator::getCurrentPage() : '');
    $key = 'route-'.Str::slug(Request::url()).$page;
    if(is_null($response) && Cache::has($key) && App::environment() != 'local' && Config::get('app.debug') != 'true')
        return Cache::get($key);
    elseif(!is_null($response) && !Cache::has($key) && App::environment() != 'local' && Config::get('app.debug') != 'true')
        Cache::put($key, $response->getContent(), 30);