Share on facebook
Share on twitter
Share on linkedin

How To Use Memcache in Laravel

With caching, you get to store data for easy access, so future demands for that data can be quickly satisfied. Data stored in a cache may be from a prior computation or duplicated from elsewhere. So whenever the same result is needed, you can just use the cached value without a repeated computation. It’s a great way to optimize for speed and performance.

In this piece, you’ll learn how to use the Memcache framework to cache data for your Laravel site without a hitch.

What is Laravel Caching?

Laravel underpins well-known caching backends like Memcached and Redis out of the box. It also offers a unified API for different caching frameworks. You can find the cache setup at app/config/cache.php. In this record, you’ll specify which cache driver you’d like utilized by default all through your application.

Laravel offers incredible caching backends and drivers that you can switch between, depending on your use case, to improve your application performance and load time.

When new data is cached, Laravel makes an encrypted file with the information and the cache key. The same thing happens when the client is attempting to recover the content. The Laravel cache looks through the folder for the required key and then returns the found content.

Join Our Small Business Community

Get the latest news, resources and tips to help you and your small business succeed.

The cache setup record contains many other choices which are reported inside the record, so make sure to study these alternatives. Laravel is arranged to utilize the record cache driver by default, which stores serialized, cached objects within the filesystem. For bigger applications, it is recommended that you use an in-memory cache such as Memcached or APC.

What is Laravel Memcached?

Memcached is a free and open-source program authorized by the Changed BSD permit.

This general-purpose disseminated memory-caching framework speeds up dynamic database-driven websites by caching information and objects in the RAM to decrease the number of times an external information source must be read.

Within the Memcached framework, each cache comprises a key, an expiration time, optional flags, and raw information. When something is requested, Memcached checks the request time before returning it to the client. The cache is upgraded at the same time as the database.

By default, Memcached acts as a Least Recently Used cache with expiration timeouts. If the server runs out of memory, it looks for expired items to replace or use laravel clear cache. If extra memory is still required, Memcached replaces items that have not been requested for a certain length of time during the termination timeout period or longer, retaining more recently requested data in memory.

Why is Caching Important?

For the most part, caches keep track of frequent reactions to client requests. They also store the results of extended computational operations.

Here’s how caching helps:

  • Caching data dramatically speeds up application execution.
  • It allows browsers and websites to load faster since access elements like homepage pictures have already been downloaded.
  • Caching is faster than accessing the main memory every time something has to be retrieved.
  • It also increases the speed of accessing data, and improves CPU performance.
  • And since most recent data is stored in the cache, the outputs are faster.

Learn How To Use Memcache in Laravel

Cache Usage

Storing an item in the cache

Cache::put(‘key’, ‘value’, $minutes);

Using carbon objects to set expire time

$expiresAt = Carbon::now()->addMinutes(10);

Cache::put(‘key’, ‘value’, $expiresAt);

Storing an item in the cache if it doesn’t exist

Cache::add(‘key’, ‘value’, $minutes);

The add method will return true if the item is actually added to the cache. Otherwise, the method will return false.

Checking for existence in cache

if (Cache::has(‘key’))

{

//

}

Retrieving an item from the cache

$value = Cache::get(‘key’);

Retrieving an item or returning a default value

$value = Cache::get(‘key’, ‘default’);

$value = Cache::get(‘key’, function() { return ‘default’; });

Storing an item in the cache permanently

Cache::forever(‘key’, ‘value’);

Sometimes you may wish to retrieve an item from the cache, but also store a default value if the requested item doesn’t exist. For this, use the Cache::remember method:

$value = Cache::remember(‘users’, $minutes, function()

{

return DB::table(‘users’)->get();

});

You may also combine the remember and forever methods:

$value = Cache::rememberForever(‘users’, function()

{

return DB::table(‘users’)->get();

});

Note that all items stored in the cache are serialized, so you are free to store any type of data.

Pulling an item from the cache

If you need to retrieve an item from the cache and then delete it, you may use the pull method:

$value = Cache::pull(‘key’);

Removing an item from the cache

Cache::forget(‘key’);

Access specific cache stores

When using multiple cache stores, you may access them via the store method:

$value = Cache::store(‘foo’)->get(‘key’);

Increments & Decrements

All drivers except database support the increment and decrement operations:

Incrementing a value

Cache::increment(‘key’);

 

Cache::increment(‘key’, $amount);

Decrementing a value

Cache::decrement(‘key’);

Cache::decrement(‘key’, $amount);

Cache Tags

Accessing a tagged cache

Cache tags let you tag related items in the cache, and then flush all caches tagged with a given name. To access a tagged cache, use the tags method.

You may store a tagged cache by passing in an ordered list of tag names as arguments, or as an ordered array of tag names:

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

Cache::tags([‘people’, ‘artists’])->put(‘Anne’, $anne, $minutes);

$anne = Cache::tags(‘people’, ‘artists’)->get(‘Anne’);

$john = Cache::tags([‘people’, ‘authors’])->get(‘John’);

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

Cache::tags(‘authors’)->flush();

Cache Events

To execute code on every cache operation, you may listen for the events fired by the cache:

Event::listen(‘cache.hit’, function($key, $value) {

//

});

 

Event::listen(‘cache.missed’, function($key) {

//

});

 

Event::listen(‘cache.write’, function($key, $value, $minutes) {

//

});

 

Event::listen(‘cache.delete’, function($key) {

//

});

Database Cache

When using the database cache driver, set up a table to contain the cache items. You’ll find an example Schema declaration for the table below:

Schema::create(‘cache’, function($table)

{

$table->string(‘key’)->unique();

$table->text(‘value’);

$table->integer(‘expiration’);

});

The default configuration uses TCP/IP based on Memcached::addServer:

‘memcached’ => array(

array(‘host’ => ‘127.0.0.1’, ‘port’ => 11211, ‘weight’ => 100),

),

‘memcached’ => array(

array(‘host’ => ‘/var/run/memcached/memcached.sock’, ‘port’ => 0, ‘weight’ => 100),

),

Conclusion

Caching plays a vital role in optimizing the execution of your web apps; it speeds up the site and decreases load times. Advanced Laravel caching tools are a great way to speed up your apps. With Memcache, your web apps execution is sure to skyrocket!

Join Our Small Business Community

Get the latest news, resources and tips to help you and your small business succeed.

RECENT POST