What is caching?
Some tasks—database queries, external API calls, heavy computations—take time on every request. Caching stores the result so future requests return the data instantly from a fast store like Redis or Memcached. Laravel provides a unified caching API that works across multiple backends, so you can switch drivers without changing your application code.Configuration
Cache configuration lives inconfig/cache.php. Set the default driver with the CACHE_STORE environment variable:
Cache driver hierarchy
Choose a driver based on the speed and infrastructure requirements of your application:Database driver
Thedatabase driver stores cached data in a database table. New Laravel projects include the migration automatically. If yours doesn’t, create the table:
Redis driver
Install Predis and set the driver:Storage driver
Thestorage driver lets you store cached values on any configured filesystem disk. Use it when you want to reuse an existing disk, such as S3, as a key/value cache store:
Retrieving items
Use theCache facade to interact with the cache:
Accessing multiple stores
Switch stores on the fly withCache::store:
Storing items
Retrieve and store (remember)
The most common caching pattern: retrieve from cache, or compute and store if missing:How remember() works
Store the result forever if it doesn’t exist:rememberWithWarmth method. This method returns an array containing the cached value and a boolean indicating whether the item was “warm”, meaning it was retrieved from the cache and not resolved from the closure:
Stale-while-revalidate (flexible)
Serve a slightly stale value while recomputing in the background, so no user waits for recalculation:Removing items
Incrementing and decrementing
Atomically adjust integer values without a full read-write cycle:Cache tags
Tags let you group related cache items and flush them together. Tags are only available with Redis or Memcached drivers and are not supported by thefile, dynamodb, database, or storage drivers:
How cache tags work
Items tagged with multiple tags can be flushed by any of their tags:Atomic locks
Atomic locks prevent race conditions when multiple processes compete to perform the same task. The lock is released automatically when the closure finishes, even if an exception is thrown:block to wait for a lock to become available:
Locks across processes
Acquire a lock in one process and release it in another by passing a token:Refreshing Locks
Extend a lock you currently own using therefresh method. If no duration is given, the original expiration is reused. Useful for long-running loops where you prefer a short lock renewed periodically:
Caching in practice
1
Identify slow queries
Find database calls or API requests that run on every page load with similar inputs.
2
Wrap with remember
3
Invalidate when data changes