Cache

Configuration

Laravel provides a unified API for various caching systems. The cache configuration is located at config/cache.php. In this file you may specify which cache driver you would like used by default throughout your application. Laravel supports popular caching backends like Memcached and Redis out of the box.

The cache configuration file also contains various other options, which are documented within the file, so make sure to read over these options. By default, Laravel is configured to use the file cache driver, which stores the serialized, cached objects in the filesystem. For larger applications, it is recommended that you use an in-memory cache such as Memcached or APC. You may even configure multiple cache configurations for the same driver.

Cache Prerequisites

Database

When using the database cache driver, you will need to setup a table to contain the cache items. You'll find an example Schema declaration for the table below:

  1. Schema::create('cache', function($table) {
  2. $table->string('key')->unique();
  3. $table->text('value');
  4. $table->integer('expiration');
  5. });

Memcached

Using the Memcached cache requires the Memcached PECL package to be installed.

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

  1. 'memcached' => [
  2. [
  3. 'host' => '127.0.0.1',
  4. 'port' => 11211,
  5. 'weight' => 100
  6. ],
  7. ],

You may also set the host option to a UNIX socket path. If you do this, the port option should be set to 0:

  1. 'memcached' => [
  2. [
  3. 'host' => '/var/run/memcached/memcached.sock',
  4. 'port' => 0,
  5. 'weight' => 100
  6. ],
  7. ],

Redis

Before using a Redis cache with Laravel, you will need to install the predis/predis package (~1.0) via Composer.

For more information on configuring Redis, consult its Laravel documentation page.

Cache Usage

Obtaining A Cache Instance

The Illuminate\Contracts\Cache\Factory and Illuminate\Contracts\Cache\Repository contracts provide access to Laravel's cache services. The Factory contract provides access to all cache drivers defined for your application. The Repository contract is typically an implementation of the default cache driver for your application as specified by your cache configuration file.

However, you may also use the Cache facade, which is what we will use throughout this documentation. The Cache facade provides convenient, terse access to the underlying implementations of the Laravel cache contracts.

For example, let's import the Cache facade into a controller:

  1. <?php
  2. namespace App\Http\Controllers;
  3. use Cache;
  4. use Illuminate\Routing\Controller;
  5. class UserController extends Controller
  6. {
  7. /**
  8. * Show a list of all users of the application.
  9. *
  10. * @return Response
  11. */
  12. public function index()
  13. {
  14. $value = Cache::get('key');
  15. //
  16. }
  17. }

Accessing Multiple Cache Stores

Using the Cache facade, you may access various cache stores via the store method. The key passed to the store method should correspond to one of the stores listed in the stores configuration array in your cache configuration file:

  1. $value = Cache::store('file')->get('foo');
  2. Cache::store('redis')->put('bar', 'baz', 10);

Retrieving Items From The Cache

The get method on the Cache facade is used to retrieve items from the cache. If the item does not exist in the cache, null will be returned. If you wish, you may pass a second argument to the get method specifying the custom default value you wish to be returned if the item doesn't exist:

  1. $value = Cache::get('key');
  2. $value = Cache::get('key', 'default');

You may even pass a Closure as the default value. The result of the Closure will be returned if the specified item does not exist in the cache. Passing a Closure allows you to defer the retrieval of default values from a database or other external service:

  1. $value = Cache::get('key', function() {
  2. return DB::table(...)->get();
  3. });

Checking For Item Existence

The has method may be used to determine if an item exists in the cache:

  1. if (Cache::has('key')) {
  2. //
  3. }

Incrementing / Decrementing Values

The increment and decrement methods may be used to adjust the value of integer items in the cache. Both of these methods optionally accept a second argument indicating the amount by which to increment or decrement the item's value:

  1. Cache::increment('key');
  2. Cache::increment('key', $amount);
  3. Cache::decrement('key');
  4. Cache::decrement('key', $amount);

Retrieve Or Update

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 example, you may wish to retrieve all users from the cache or, if they don't exist, retrieve them from the database and add them to the cache. You may do this using the Cache::remember method:

  1. $value = Cache::remember('users', $minutes, function() {
  2. return DB::table('users')->get();
  3. });

If the item does not exist in the cache, the Closure passed to the remember method will be executed and its result will be placed in the cache.

You may also combine the remember and forever methods:

  1. $value = Cache::rememberForever('users', function() {
  2. return DB::table('users')->get();
  3. });

Retrieve And Delete

If you need to retrieve an item from the cache and then delete it, you may use the pull method. Like the get method, null will be returned if the item does not exist in the cache:

  1. $value = Cache::pull('key');

Storing Items In The Cache

You may use the put method on the Cache facade to store items in the cache. When you place an item in the cache, you will need to specify the number of minutes for which the value should be cached:

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

Instead of passing the number of minutes until the item expires, you may also pass a PHP DateTime instance representing the expiration time of the cached item:

  1. $expiresAt = Carbon::now()->addMinutes(10);
  2. Cache::put('key', 'value', $expiresAt);

The add method will only add the item to the cache if it does not already exist in the cache store. The method will return true if the item is actually added to the cache. Otherwise, the method will return false:

  1. Cache::add('key', 'value', $minutes);

The forever method may be used to store an item in the cache permanently. These values must be manually removed from the cache using the forget method:

  1. Cache::forever('key', 'value');

Removing Items From The Cache

You may remove items from the cache using the forget method on the Cache facade:

  1. Cache::forget('key');

You may clear the entire cache using the flush method:

  1. Cache::flush();

Flushing the cache does not respect the cache prefix and will remove all entries from the cache. Consider this carefully when clearing a cache which is shared by other applications.

Adding Custom Cache Drivers

To extend the Laravel cache with a custom driver, we will use the extend method on the Cache facade, which is used to bind a custom driver resolver to the manager. Typically, this is done within a service provider.

For example, to register a new cache driver named "mongo":

  1. <?php
  2. namespace App\Providers;
  3. use Cache;
  4. use App\Extensions\MongoStore;
  5. use Illuminate\Support\ServiceProvider;
  6. class CacheServiceProvider extends ServiceProvider
  7. {
  8. /**
  9. * Perform post-registration booting of services.
  10. *
  11. * @return void
  12. */
  13. public function boot()
  14. {
  15. Cache::extend('mongo', function($app) {
  16. return Cache::repository(new MongoStore);
  17. });
  18. }
  19. /**
  20. * Register bindings in the container.
  21. *
  22. * @return void
  23. */
  24. public function register()
  25. {
  26. //
  27. }
  28. }

The first argument passed to the extend method is the name of the driver. This will correspond to your driver option in the config/cache.php configuration file. The second argument is a Closure that should return an Illuminate\Cache\Repository instance. The Closure will be passed an $app instance, which is an instance of the service container.

The call to Cache::extend could be done in the boot method of the default App\Providers\AppServiceProvider that ships with fresh Laravel applications, or you may create your own service provider to house the extension - just don't forget to register the provider in the config/app.php provider array.

To create our custom cache driver, we first need to implement the Illuminate\Contracts\Cache\Store contract contract. So, our MongoDB cache implementation would look something like this:

  1. <?php
  2. namespace App\Extensions;
  3. class MongoStore implements \Illuminate\Contracts\Cache\Store
  4. {
  5. public function get($key) {}
  6. public function put($key, $value, $minutes) {}
  7. public function increment($key, $value = 1) {}
  8. public function decrement($key, $value = 1) {}
  9. public function forever($key, $value) {}
  10. public function forget($key) {}
  11. public function flush() {}
  12. public function getPrefix() {}
  13. }

We just need to implement each of these methods using a MongoDB connection. Once our implementation is complete, we can finish our custom driver registration:

  1. Cache::extend('mongo', function($app) {
  2. return Cache::repository(new MongoStore);
  3. });

Once your extension is complete, simply update your config/cache.php configuration file's driver option to the name of your extension.

If you're wondering where to put your custom cache driver code, consider making it available on Packagist! Or, you could create an Extensions namespace within your app directory. However, keep in mind that Laravel does not have a rigid application structure and you are free to organize your application according to your preferences.

Cache Tags

Note: Cache tags are not supported when using the file or database cache drivers. Furthermore, when using multiple tags with caches that are stored "forever", performance will be best with a driver such as memcached, which automatically purges stale records.

Storing Tagged Cache Items

Cache tags allow you to tag related items in the cache and then flush all cached values that assigned a given tag. You may access a tagged cache by passing in an ordered array of tag names. For example, let's access a tagged cache and put value in the cache:

  1. Cache::tags(['people', 'artists'])->put('John', $john, $minutes);
  2. Cache::tags(['people', 'authors'])->put('Anne', $anne, $minutes);

However, you are not limited to the put method. You may use any cache storage method while working with tags.

Accessing Tagged Cache Items

To retrieve a tagged cache item, pass the same ordered list of tags to the tags method:

  1. $john = Cache::tags(['people', 'artists'])->get('John');
  2. $anne = Cache::tags(['people', 'authors'])->get('Anne');

You may flush all items that are assigned a tag or list of tags. For example, this statement would remove all caches tagged with either people, authors, or both. So, both Anne and John would be removed from the cache:

  1. Cache::tags(['people', 'authors'])->flush();

In contrast, this statement would remove only caches tagged with authors, so Anne would be removed, but not John.

  1. Cache::tags('authors')->flush();

Cache Events

To execute code on every cache operation, you may listen for the events fired by the cache. Typically, you should place these event listeners within the boot method of your EventServiceProvider:

  1. /**
  2. * Register any other events for your application.
  3. *
  4. * @param \Illuminate\Contracts\Events\Dispatcher $events
  5. * @return void
  6. */
  7. public function boot(DispatcherContract $events)
  8. {
  9. parent::boot($events);
  10. $events->listen('cache.hit', function ($key, $value) {
  11. //
  12. });
  13. $events->listen('cache.missed', function ($key) {
  14. //
  15. });
  16. $events->listen('cache.write', function ($key, $value, $minutes) {
  17. //
  18. });
  19. $events->listen('cache.delete', function ($key) {
  20. //
  21. });
  22. }