Configuration
To use MongoDB as a back end forLaravel Cache and Locks,add a store configuration by specifying themongodb driver inconfig/cache.php:
'stores' => [ 'mongodb' => [ 'driver' =>'mongodb', 'connection' =>'mongodb', 'collection' =>'cache', 'lock_connection' =>'mongodb', 'lock_collection' =>'cache_locks', 'lock_lottery' => [2,100], 'lock_timeout' =>86400, ], ],
To configure themongodb database connection, see theConnection Guide section.
The following table describes a list of cache and lock optionsand their default values:
Setting | Description |
|---|---|
| Required. Specifies the lock driver to use. Must be |
| Required. The database connection used to store cache items. It must be a |
| Default |
| Default to the cache |
| Default |
| Default |
| Default |
Set Up Auto-Expiration Indexes
TheTTL indexes integrated into MongoDB automaticallydelete documents when they expire. Their use is optional with themongodbdriver, but recommended. The indexes provide better performance by delegating thedeletion of expired documents to MongoDB instead of requiring the application toperform this task.
Create the indexes with a migration that calls thecreateTTLIndex() methods provided by both the cache, and the lock stores:
<?php useIlluminate\Database\Migrations\Migration; useIlluminate\Support\Facades\Cache; returnnewclassextendsMigration { publicfunctionup():void { $store =Cache::store('mongodb'); $store->createTTLIndex(); $store->lock('')->createTTLIndex(); } };
Then run the migration:
php artisan migrate
Alternatively, you can create the index by usingMongoDB Shell (mongosh):
db.cache.createIndex( /* Field that holdsthe expiration date */ {expires_at:1 }, /* Delay to removeitems after expiration */ {expireAfterSeconds:0 } )
If you use Locks, disablelock_lottery by setting the probability to0:
'stores' => [ 'mongodb' => [ 'driver' =>'mongodb', 'connection' =>'mongodb', 'lock_lottery' => [0,100],// Disabled ], ],
Using MongoDB Cache
The Laravel cache can be used to store any serializable data using the facadeIlluminate\Support\Facades\Cache.
This example performs the following actions:
Gets the cache repository with the
mongodbstoreTries to read and return the cache item named
fooIf missing, calls the closure to compute the value, stores the value forever, and returns it
useIlluminate\Support\Facades\Cache; $value =Cache::store('mongodb')->get('foo', function () { return [1,2,3]; });
By default, cached objects do not expire. However, it is possible to define an expiry time, as shown in the following example:
Cache::store('mongodb')->set('foo','abc','1 day');
Incrementing and decrementing a value is also supported if the value isinitialized before. The following example initializes the counter to3,adds 5, and removes 2.
Cache::store('mongodb')->set('counter',3); Cache::store('mongodb')->increment('counter',5); Cache::store('mongodb')->decrement('counter',2);
Note
The Laravel Integration supports incrementing and decrementing with integer and float values.
For more information about using the cache, see theLaravel Cache documentation.
Configuring MongoDB as the Default Cache
To use themongodb store by default, change the default store inconfig/cache.php.
return [ 'default' =>env('CACHE_STORE','mongodb'), 'stores' => [ 'mongodb' => [ 'driver' =>'mongodb', 'connection' =>'mongodb', ], ], ];
Note
We have deliberately omitted all optional parameters in the previous example,so the default values are applied.
TheCACHE_STORE variable can be set in your environment or inthe.env file. Update or remove it as follows:
CACHE_STORE=mongodb
Then you can use theIlluminate\Support\Facades\Cache facade andautomatic injection:
useIlluminate\Support\Facades\Cache; Cache::get('foo',5);
The following example shows how to use automatic injection of the cachemanager by using the default store. The example creates a controller thatincrements a counter each time it is invoked.
<?php namespaceApp\Http\Controllers; useApp\Contracts\CacheManager; classCountControllerextendsController { publicfunction__construct( private CacheManager$cache, ){} publicfunctionhit():int { return$this->cache->increment('counter'); } }
Using MongoDB Lock
Atomic locks allow for the manipulation of distributed locks without worryingabout race conditions. The following example implements an atomic lock:
useIlluminate\Support\Facades\Cache; $lock =Cache::store('mongodb')->lock('foo',10); if ($lock->get()) { // Lock acquired for10 seconds... $lock->release(); }
For more information on using locks, see theLaravel Locks documentation.