Cache

    Some of the data retrieval or processing tasks performed by your application could be CPU intensive or take several seconds to complete. When this is the case, it is common to cache the retrieved data for a time so it can be retrieved quickly on subsequent requests for the same data. The cached data is usually stored in a very fast data store such as or Redis.

    Thankfully, Laravel provides an expressive, unified API for various cache backends, allowing you to take advantage of their blazing fast data retrieval and speed up your web application.

    Configuration

    Your application’s cache configuration file is located at . In this file, you may specify which cache driver you would like to be used by default throughout your application. Laravel supports popular caching backends like , Redis, , and relational databases out of the box. In addition, a file based cache driver is available, while array and “null” cache drivers provide convenient cache backends for your automated tests.

    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 on the server’s filesystem. For larger applications, it is recommended that you use a more robust driver such as Memcached or Redis. You may even configure multiple cache configurations for the same driver.

    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:

    Memcached

    Using the Memcached driver requires the to be installed. You may list all of your Memcached servers in the config/cache.php configuration file. This file already contains a memcached.servers entry to get you started:

    1. 'memcached' => [
    2. 'servers' => [
    3. [
    4. 'host' => env('MEMCACHED_HOST', '127.0.0.1'),
    5. 'port' => env('MEMCACHED_PORT', 11211),
    6. 'weight' => 100,
    7. ],
    8. ],
    9. ],

    If needed, you may 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 either install the PhpRedis PHP extension via PECL or install the predis/predis package (~1.0) via Composer. Laravel Sail already includes this extension. In addition, official Laravel deployment platforms such as and Laravel Vapor have the PhpRedis extension installed by default.

    For more information on configuring Redis, consult its .

    DynamoDB

    Before using the DynamoDB cache driver, you must create a DynamoDB table to store all of the cached data. Typically, this table should be named cache. However, you should name the table based on the value of the stores.dynamodb.table configuration value within your application’s cache configuration file.

    This table should also have a string partition key with a name that corresponds to the value of the stores.dynamodb.attributes.key configuration item within your application’s cache configuration file. By default, the partition key should be named key.

    Obtaining A Cache Instance

    To obtain a cache store instance, you may 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:

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

    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', 600); // 10 Minutes

    Retrieving Items From The Cache

    The Cache facade’s get method 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 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. This method will also return false if the item exists but its value is null:

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

    Incrementing / Decrementing Values

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

    Retrieve & Store

    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', $seconds, 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 use the rememberForever method to retrieve an item from the cache or store it forever if it does not exist:

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

    Retrieve & Delete

    If you need to retrieve an item from the cache and then delete the item, 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:

    1. Cache::put('key', 'value', $seconds = 10);

    If the storage time is not passed to the put method, the item will be stored indefinitely:

    Instead of passing the number of seconds as an integer, you may also pass a DateTime instance representing the desired expiration time of the cached item:

    Store If Not Present

    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. The add method is an atomic operation:

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

    Storing Items Forever

    The forever method may be used to store an item in the cache permanently. Since these items will not expire, they must be manually removed from the cache using the forget method:

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

    {tip} If you are using the Memcached driver, items that are stored “forever” may be removed when the cache reaches its size limit.

    You may remove items from the cache using the forget method:

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

    You may also remove items by providing a zero or negative number of expiration seconds:

    1. Cache::put('key', 'value', 0);
    2. Cache::put('key', 'value', -5);

    You may clear the entire cache using the flush method:

    1. Cache::flush();

    The Cache Helper

    In addition to using the Cache facade, you may also use the global cache function to retrieve and store data via the cache. When the cache function is called with a single, string argument, it will return the value of the given key:

    1. $value = cache('key');

    If you provide an array of key / value pairs and an expiration time to the function, it will store values in the cache for the specified duration:

    1. cache(['key' => 'value'], $seconds);
    2. cache(['key' => 'value'], now()->addMinutes(10));

    When the cache function is called without any arguments, it returns an instance of the Illuminate\Contracts\Cache\Factory implementation, allowing you to call other caching methods:

    1. cache()->remember('users', $seconds, function () {
    2. return DB::table('users')->get();
    3. });

    {tip} When testing call to the global cache function, you may use the Cache::shouldReceive method just as if you were .

    Cache Tags

    Storing Tagged Cache Items

    Cache tags allow you to tag related items in the cache and then flush all cached values that have been 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 a value into the cache:

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

    Accessing Tagged Cache Items

    To retrieve a tagged cache item, pass the same ordered list of tags to the tags method and then call the get method with the key you wish to retrieve:

    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 cached values tagged with authors, so Anne would be removed, but not John:

    {note} To utilize this feature, your application must be using the memcached, redis, dynamodb, database, file, or array cache driver as your application’s default cache driver. In addition, all servers must be communicating with the same central cache server.

    Driver Prerequisites

    Database

    When using the database cache driver, you will need to setup a table to contain your application’s cache locks. You’ll find an example Schema declaration for the table below:

    1. Schema::create('cache_locks', function ($table) {
    2. $table->string('key')->primary();
    3. $table->string('owner');
    4. $table->integer('expiration');
    5. });

    Managing Locks

    Atomic locks allow for the manipulation of distributed locks without worrying about race conditions. For example, uses atomic locks to ensure that only one remote task is being executed on a server at a time. You may create and manage locks using the Cache::lock method:

    1. use Illuminate\Support\Facades\Cache;
    2. $lock = Cache::lock('foo', 10);
    3. if ($lock->get()) {
    4. // Lock acquired for 10 seconds...
    5. $lock->release();
    6. }

    The get method also accepts a closure. After the closure is executed, Laravel will automatically release the lock:

    1. Cache::lock('foo')->get(function () {
    2. // Lock acquired indefinitely and automatically released...
    3. });

    If the lock is not available at the moment you request it, you may instruct Laravel to wait for a specified number of seconds. If the lock can not be acquired within the specified time limit, an Illuminate\Contracts\Cache\LockTimeoutException will be thrown:

    1. use Illuminate\Contracts\Cache\LockTimeoutException;
    2. $lock = Cache::lock('foo', 10);
    3. try {
    4. $lock->block(5);
    5. // Lock acquired after waiting a maximum of 5 seconds...
    6. } catch (LockTimeoutException $e) {
    7. // Unable to acquire lock...
    8. } finally {
    9. optional($lock)->release();
    10. }

    The example above may be simplified by passing a closure to the block method. When a closure is passed to this method, Laravel will attempt to acquire the lock for the specified number of seconds and will automatically release the lock once the closure has been executed:

    1. Cache::lock('foo', 10)->block(5, function () {
    2. // Lock acquired after waiting a maximum of 5 seconds...
    3. });

    Managing Locks Across Processes

    Sometimes, you may wish to acquire a lock in one process and release it in another process. For example, you may acquire a lock during a web request and wish to release the lock at the end of a queued job that is triggered by that request. In this scenario, you should pass the lock’s scoped “owner token” to the queued job so that the job can re-instantiate the lock using the given token.

    In the example below, we will dispatch a queued job if a lock is successfully acquired. In addition, we will pass the lock’s owner token to the queued job via the lock’s owner method:

    1. $lock = Cache::lock('processing', 120);
    2. if ($lock->get()) {
    3. ProcessPodcast::dispatch($podcast, $lock->owner());
    4. }

    Within our application’s job, we can restore and release the lock using the owner token:

    1. Cache::restoreLock('processing', $this->owner)->release();

    If you would like to release a lock without respecting its current owner, you may use the forceRelease method:

    1. Cache::lock('processing')->forceRelease();

    Adding Custom Cache Drivers

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

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

    We just need to implement each of these methods using a MongoDB connection. For an example of how to implement each of these methods, take a look at the Illuminate\Cache\MemcachedStore in the Laravel framework source code. Once our implementation is complete, we can finish our custom driver registration by calling the Cache facade’s extend method:

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

    Registering The Driver

    To register the custom cache driver with Laravel, we will use the extend method on the Cache facade. Since other service providers may attempt to read cached values within their boot method, we will register our custom driver within a booting callback. By using the booting callback, we can ensure that the custom driver is registered just before the boot method is called on our application’s service providers but after the register method is called on all of the service providers. We will register our booting callback within the register method of our application’s App\Providers\AppServiceProvider class:

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

    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 .

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

    1. /**
    2. * The event listener mappings for the application.
    3. *
    4. * @var array
    5. */
    6. protected $listen = [
    7. 'Illuminate\Cache\Events\CacheHit' => [
    8. 'App\Listeners\LogCacheHit',
    9. ],
    10. 'Illuminate\Cache\Events\CacheMissed' => [
    11. 'App\Listeners\LogCacheMissed',
    12. ],
    13. 'Illuminate\Cache\Events\KeyForgotten' => [
    14. 'App\Listeners\LogKeyForgotten',
    15. ],
    16. 'Illuminate\Cache\Events\KeyWritten' => [
    17. 'App\Listeners\LogKeyWritten',
    18. ];