Cache in Laravel

In this tutorial i am going to walk you through using cache in laravel. Cache is basically an another layer between our website and database. Database queries can be slow, especially when we have lots of traffic.The cache layer basically act as a middle layer to store data that has not been changed between requests. Retrieving data from cache rather than a database is much quicker . There are all kinds of ways to cache data, and laravel makes it easy to do so with small number of method calls.

Cache Configuration in Laravel

Laravel provides a unified API for various caching systems. There is no need to change our code if we want to change between different caching systems. All the cache configuration located at app/config/cache.php. As we can see by default laravel uses file storage system for cache. The other caching systems options are memcached, apc, redis, array and database. For large applications, it is recommended that you use an in-memory cache system such as Memcachedor APC​.

// app/config/cache.php
<?php
return array(
/*
|--------------------------------------------------------------------------
| Default Cache Driver
|--------------------------------------------------------------------------
|
| This option controls the default cache "driver" that will be used when
| using the Caching library. Of course, you may use other drivers any
| time you wish. This is the default when another is not specified.
|
| Supported: "file", "database", "apc", "memcached", "redis", "array"
|
*/
'driver' => 'file',
/*
|--------------------------------------------------------------------------
| File Cache Location
|--------------------------------------------------------------------------
|
| When using the "file" cache driver, we need a location where the cache
| files may be stored. A sensible default has been specified, but you
| are free to change it to any other place on disk that you desire.
|
*/
'path' => storage_path().'/cache',
/*
|--------------------------------------------------------------------------
| Database Cache Connection
|--------------------------------------------------------------------------
|
| When using the "database" cache driver you may specify the connection
| that should be used to store the cached items. When this option is
| null the default database connection will be utilized for cache.
|
*/
'connection' => null,
/*
|--------------------------------------------------------------------------
| Database Cache Table
|--------------------------------------------------------------------------
|
| When using the "database" cache driver we need to know the table that
| should be used to store the cached items. A default table name has
| been provided but you're free to change it however you deem fit.
|
*/
'table' => 'cache',
/*
|--------------------------------------------------------------------------
| Memcached Servers
|--------------------------------------------------------------------------
|
| Now you may specify an array of your Memcached servers that should be
| used when utilizing the Memcached cache driver. All of the servers
| should contain a value for "host", "port", and "weight" options.
|
*/
'memcached' => array(
array('host' => '127.0.0.1', 'port' => 11211, 'weight' => 100),
),
/*
|--------------------------------------------------------------------------
| Cache Key Prefix
|--------------------------------------------------------------------------
|
| When utilizing a RAM based store such as APC or Memcached, there might
| be other applications utilizing the same cache. So, we'll specify a
| value to get prefixed to all our keys so we can avoid collisions.
|
*/
'prefix' => 'laravel',
);

If we observe carefully cache config file, we can see where the cache data is going to be stored. Based on the cache driver our cache is going to be stored in either app/storage/cache or cache table or memcached servers.

Laravel Cache Example

Let's test some functionality with few examples in routes.php file.

Cache::put()

The first method we will take a look at is Cache::put() method. This method takes three parameters cachekey, value and time in minutes.

Cache::put('key', 'value', $minutes);

Now let's store some value in cache and see what will happen.

Route::get('/', function()
{
return Cache::put('cachekey', ' I am first one to go into cache', 2);
});

Now if you go to the route / URL we won't see anything. But if you go to app/storage/cache folder there will be sub folders inside them it will create a file with name something like this 773d6310cb469462e79d0f7ff0a55840​. On opening that file we can the data has been cached and stored in this way 1418639298s:32:" I am first one to go into cache";​

Cache::get()

Now we have an item cached but we want to retrieve it. This how we can do it using Cache::get() method.

Route::get('/', function()
{
return Cache::get('cachekey');
});

Now if you vist index again , we will see the output like below.

I am first one to go into cache

If we don't see any output that means the cache has been expired so it's better to send a default value. let's find out how we can keep a default value.

So now what we have saw was cache was expired before we go and retrieve the cached value using the cache key. I think it's better if we know how we can cache an item forever. Let's see how we can do that.

Cache::forever()

Route::get('/', function()
{
return Cache::forever('cachekey', ' I am first one to go into cache');
});

Cache::has()

I think it's better to check before we access a cached item was exist or not for that we have a method called Cache::has(). Let's see how we can use it.

We can also cache database results using some of the advanced methods called Cache::remember() and Cache::rememberForever(). Let's explain this with a small example, suppose we want to cache all the posts of a blog for certain time we can do it like below.

We can't use the increment and decrement methods with file or database caching systems.

Cache Tags

Laravel also allows us to group data together so that we can flush sections of cached data at a single time using tags. This is lot useful when we need to invalidate each single item one by one. So it's better we use tag words for caching.Again this also can't use with file or database caching systems. We need to use Memcached running in your local system to use this.

Adding an item using tags to the cache.

Cache::tags('people', 'authors')->put('John', $john, $minutes);

Accessing an item from tagged cache

$results = Cache::tags('people', 'artists')->get('Anne');

To flush all the cached items in a single time using a tag words.

Cache::tags('people', 'authors')->flush();

This is how we do caching in laravel. Laravel doing lot of stuff for the developers. If you don't use cache at start then later it will bite you in the back when you get lot of traffic.

Author

Imran is a web developer and consultant from India. He is the founder of KodeInfo, the PHP and Laravel Community . In the meantime he follows other projects, works as a freelance backend consultant for PHP applications and studies IT Engineering . He loves to learn new things, not only about PHP or development but everything.

About Us

We develop custom web apps with architecture that is carefully engineered
and tested for optimum use of Memcache to balance the read/write activity for the lowest
possible CPU usage on the server. We use the best programming languages and Frameworks
for the app, such as Laravel (PHP), Angular JS (Javascript) or RoR (Ruby).