KodeInfo | Learning resources for web and mobile development

Cache in Laravel

December 15th, 2014 11:39:47 by Imran Iqbal Comments(0) - Views(8671)

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 Memcached or 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.

Route::get('/', function()
{

     return Cache::get('cachekey', 'The cache has been empty');

});

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.

Route::get('/', function()
{

     if(Cache::has('cachekey'))
     {
            return Cache::get('cachekey');
      }

});

Cache::forget()

We have cached an item forever using Cache::forever() method what if we want to remove it, for that we have a another method called Cache::forget()

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

     if(Cache::has('cachekey'))
     {
            return Cache::get('cachekey');
     }else{
            return 'cache was forgotten, so this is some random data';
     }
});           

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.

$posts = Cache::remember('posts',60, function()
{
   return DB::table('posts')->get();
});

$posts = Cache::rememberForever('posts', function()
{
   return DB::table('posts')->get();
});

Increment and Decrement

Cache is useful when increment and decrement values, it's quit difficult to always hit database. So we can use laravel methods increment() and decrement() .

Cache::increment('cachekey'); //increment by 1

Cache::increment('cachekey' 10); //increment by 10

Cache::decrement('cachekey'); // decrement by 1

Cache::decrement('cachekey' 10); //decrement by 10

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. 

Thanks for reading my tutorial.

Kode Info

 

Author

  • Imran Iqbal
    Imran Iqbal

    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.

Related

WHY USE A FRAMEWORK OVER PLAIN PHP

WHY USE A FRAMEWORK OVER PLAIN PHP
read more

GETTING STARTED WITH LARAVEL

GETTING STARTED WITH LARAVEL
read more

UNDERSTANDING LARAVEL STRUCTURE

UNDERSTANDING LARAVEL STRUCTURE
read more

UNDERSTANDING LARAVEL ROUTES

UNDERSTANDING LARAVEL ROUTES
read more

comments powered by Disqus