Cache
Introduction
Some of the work your application performs can be slow or expensive, such as generating a multi-second report or calling a rate-limited external API. When that data doesn't change on every request, you can cache it for a period of time so subsequent requests read the stored value instead of repeating the work.
Laravel provides a single, unified API across every cache backend, allowing you to start with the in-memory store and move to a database or Redis without changing your application code. For example, this dashboard handler counts users at most once every 10 minutes:
1use laravel::cache;2use laravel::prelude::*;34use crate::models::User;56pub async fn show() -> laravel::Result<String> {7 let users: u64 = cache::remember("users:count", 10.minutes(), async || {8 User::query().count().await9 })10 .await?;1112 Ok(format!("{users} users"))13}1use laravel::cache;2use laravel::prelude::*;34use crate::models::User;56pub async fn show() -> laravel::Result<String> {7 let users: u64 = cache::remember("users:count", 10.minutes(), async || {8 User::query().count().await9 })10 .await?;1112 Ok(format!("{users} users"))13}
Configuration
The CACHE_STORE environment variable selects the default store used by the functions in laravel::cache. Laravel includes several built-in stores:
| Store | Storage |
|---|---|
memory |
In each process's memory for the lifetime of the process. Laravel uses it when CACHE_STORE isn't set. |
database |
In a shared database table configured for the database store. |
redis |
In a shared Redis server configured for the Redis store. |
failover |
In the database store, falling back to memory when failing over. |
discard |
Nowhere. Every read misses, effectively disabling caching. |
New applications use the database store, so every process and server shares cached data:
1CACHE_STORE=database1CACHE_STORE=database
The memory store works well when your application runs on a single server and doesn't need its cache to survive a restart.
CACHE_PREFIX is prepended to every cache key so multiple applications sharing a store don't collide. It defaults to a prefix derived from your application's name, such as my_app_cache_.
The database store
The database store keeps cached values in a cache table and atomic locks in a cache_locks table. New applications create both tables in their create_cache_table migration, which holds only the cache::tables! macro:
1// database/migrations/0001_01_01_000001_create_cache_table.rs2laravel::cache::tables!();1// database/migrations/0001_01_01_000001_create_cache_table.rs2laravel::cache::tables!();
Run your migrations before using the database store:
1laravel migrate1laravel migrate
By default, the database store uses your default database connection. You may point it at another connection or table using DB_CACHE_CONNECTION and DB_CACHE_TABLE, and customize locks independently with DB_CACHE_LOCK_CONNECTION and DB_CACHE_LOCK_TABLE. If you rename a table, replace the macro with the migration it stands for and change the table names to match:
1// database/migrations/0001_01_01_000001_create_cache_table.rs2use laravel::db::AnyTransaction;34pub async fn migrate(tx: &mut AnyTransaction<'_>) -> laravel::Result<()> {5 tx.schema()6 .create("cache", |table| {7 table.string("key").primary();8 table.medium_text("value");9 table.timestamp("expiration").index();10 })11 .await?;1213 tx.schema()14 .create("cache_locks", |table| {15 table.string("key").primary();16 table.string("owner");17 table.timestamp("expiration").index();18 })19 .await20}1// database/migrations/0001_01_01_000001_create_cache_table.rs2use laravel::db::AnyTransaction;34pub async fn migrate(tx: &mut AnyTransaction<'_>) -> laravel::Result<()> {5 tx.schema()6 .create("cache", |table| {7 table.string("key").primary();8 table.medium_text("value");9 table.timestamp("expiration").index();10 })11 .await?;1213 tx.schema()14 .create("cache_locks", |table| {15 table.string("key").primary();16 table.string("owner");17 table.timestamp("expiration").index();18 })19 .await20}
Laravel automatically prunes expired rows roughly once an hour, so no scheduled task is required. To prune expired entries immediately, run cache:prune (passing an optional store name to target a specific store):
1laravel cache:prune2laravel cache:prune reports1laravel cache:prune2laravel cache:prune reports
Inside a database transaction on the store's connection, cache writes participate in the transaction and roll back if the transaction fails. To keep cache writes independent of your transactions, assign the cache store a separate connection via DB_CACHE_CONNECTION.
The Redis store
The redis store keeps cached values on the cache Redis connection and locks on the default connection. It is also fully compatible with Valkey, including managed Laravel Valkey on Laravel Cloud. After enabling Laravel's redis Cargo feature (covered in the Redis guide), select the redis store in your .env file:
1CACHE_STORE=redis1CACHE_STORE=redis
Use REDIS_CACHE_CONNECTION and REDIS_CACHE_LOCK_CONNECTION if you want to route values or locks to different Redis connections. Redis expires keys automatically, so no pruning is needed.
Flushing the redis store deletes every key in that connection's Redis database, regardless of prefix. Keep the cache connection on its own Redis database, as the default configuration does. When values and locks share a database (such as on a cluster), a cached value and a lock with the same name share the same Redis key, so give them distinct names.
Failing over
If your primary cache store becomes unavailable, requests that read or write the cache will fail unless you configure failover. A failover store tries a list of stores in order, falling back to the next store whenever an operation fails. The built-in failover store tries database first, then memory:
1CACHE_STORE=failover1CACHE_STORE=failover
To fail over between other stores, define a custom failover store:
1cache.add_store("failover", StoreConfig::failover(["redis", "database"]));1cache.add_store("failover", StoreConfig::failover(["redis", "database"]));
Laravel logs a warning whenever a store starts failing. Values are not copied between stores during failover, and atomic locks never fail over: locks always target the first store in the list so locking fails cleanly while that store is down.
Defining your own stores
Most applications only need the built-in stores. When you need an additional store, such as a dedicated table for cached reports, create a src/config/cache.rs configuration file starting from Cache::from_env and add your store:
1// src/config/cache.rs2use laravel::config::cache::{Cache, DatabaseStore};3use laravel::config::{self, Env};45#[config::section]6fn cache(env: &Env) -> Cache {7 let mut cache = Cache::from_env(env);89 cache.add_store(10 "reports",11 DatabaseStore::new()12 .connection("reporting")13 .table("report_cache"),14 );1516 cache17}1// src/config/cache.rs2use laravel::config::cache::{Cache, DatabaseStore};3use laravel::config::{self, Env};45#[config::section]6fn cache(env: &Env) -> Cache {7 let mut cache = Cache::from_env(env);89 cache.add_store(10 "reports",11 DatabaseStore::new()12 .connection("reporting")13 .table("report_cache"),14 );1516 cache17}
Register the module in src/config/mod.rs:
1mod cache;1mod cache;
You can then access the store by name using cache::store("reports").
Using the cache
The top-level functions in laravel::cache operate on your default cache store. To interact with another store, call cache::store with the store's name; it returns a repository with the same methods:
1use laravel::cache;23let report: Option<String> = cache::store("reports")?.get("monthly").await?;1use laravel::cache;23let report: Option<String> = cache::store("reports")?.get("monthly").await?;
You may use the cache from handlers, middleware, console commands, queued jobs, and anywhere else your application runs. If you spawn your own async task and want to access the cache inside it, use laravel::task::spawn rather than tokio::spawn.
Retrieving items
Use cache::get to retrieve a value as the requested type. If the key is missing or expired, get returns None. You may check whether a key exists using cache::has:
1use laravel::cache;23let name: Option<String> = cache::get("user:42:name").await?;45if cache::has("user:42:name").await? {6 // ...7}1use laravel::cache;23let name: Option<String> = cache::get("user:42:name").await?;45if cache::has("user:42:name").await? {6 // ...7}
To retrieve a value and immediately remove it from the cache, use cache::pull:
1let token: Option<String> = cache::pull("invite:42").await?;1let token: Option<String> = cache::pull("invite:42").await?;
To fetch several keys in a single call, use cache::many, which returns values in the same order as the requested keys:
1let names: Vec<Option<String>> = cache::many(["user:1:name", "user:2:name"]).await?;1let names: Vec<Option<String>> = cache::many(["user:1:name", "user:2:name"]).await?;
Retrieve and store
Frequently, you'll want to read an item from the cache and compute it when it's missing. cache::remember handles both in one call: it returns the cached value if present, or runs your closure and stores the returned value for the given duration. For example, this caches published post titles for an hour:
1use laravel::cache;2use laravel::prelude::*;34use crate::models::Post;56let titles: Vec<String> = cache::remember("posts:titles", 1.hour(), async || {7 Post::query()8 .filter(!Post::published_at.is_null())9 .pluck(Post::title)10 .await11})12.await?;1use laravel::cache;2use laravel::prelude::*;34use crate::models::Post;56let titles: Vec<String> = cache::remember("posts:titles", 1.hour(), async || {7 Post::query()8 .filter(!Post::published_at.is_null())9 .pluck(Post::title)10 .await11})12.await?;
Because the closure returns a laravel::Result, you may use ? inside it. If the closure returns an error, remember propagates the error without caching anything.
If several concurrent requests miss the cache at the same time, each runs the closure. When the work should only run once at a time, coordinate it with an atomic lock.
Stale while revalidate
With remember, the first request that sees an expired entry must wait while the closure recomputes it. For slow queries or API calls, cache::flexible avoids that latency spike by serving the stale value immediately while refreshing it in the background. Pass both the fresh duration and the total grace duration:
1use laravel::cache;2use laravel::prelude::*;34use crate::models::Post;56let posts: u64 = cache::flexible("posts:count", 5.minutes(), 10.minutes(), async || {7 Post::query().count().await8})9.await?;1use laravel::cache;2use laravel::prelude::*;34use crate::models::Post;56let posts: u64 = cache::flexible("posts:count", 5.minutes(), 10.minutes(), async || {7 Post::query().count().await8})9.await?;
For the first 5 minutes, flexible returns the cached value directly. Between 5 and 10 minutes, it returns the stale value immediately while managed background work recomputes the fresh value so the request doesn't block. After 10 minutes, the entry expires and the next request recomputes it inline like remember.
Because the closure may execute after the HTTP response is sent, move or clone any captured data into the closure.
Storing items
Use cache::put to store a value for a given lifetime. Every cached item requires an expiration duration, so give values that rarely change a longer lifetime:
1use laravel::cache;2use laravel::prelude::*;3use serde_json::json;45cache::put("user:42:name", "Taylor", 10.minutes()).await?;67cache::put("settings", json!({ "theme": "dark" }), 1.day()).await?;1use laravel::cache;2use laravel::prelude::*;3use serde_json::json;45cache::put("user:42:name", "Taylor", 10.minutes()).await?;67cache::put("settings", json!({ "theme": "dark" }), 1.day()).await?;
Values are serialized as JSON, so you may store any type implementing Serialize and read it back as any type implementing Deserialize. If get finds a stored value that cannot deserialize into the requested type, it returns an error rather than None. By contrast, remember and flexible treat incompatible cached values as a miss and recompute them, so deploys that change a struct's shape recover gracefully.
Use cache::add to store a value only if the key does not already exist. The check and write happen atomically, returning true if the value was stored and false if another request beat it:
1if cache::add("report:monthly:started", true, 10.minutes()).await? {2 // This request generates the report...3}1if cache::add("report:monthly:started", true, 10.minutes()).await? {2 // This request generates the report...3}
Use cache::put_many to store several key-value pairs with a shared lifetime, and cache::touch to extend an existing key's lifetime without rewriting its value:
1cache::put_many([("user:1:name", "Taylor"), ("user:2:name", "Abigail")], 10.minutes()).await?;23cache::touch("report:monthly", 30.minutes()).await?;1cache::put_many([("user:1:name", "Taylor"), ("user:2:name", "Abigail")], 10.minutes()).await?;23cache::touch("report:monthly", 30.minutes()).await?;
Counters
Use cache::increment_or_add to increment an integer counter, creating it with the given initial amount and lifetime if it doesn't exist yet, and returning the new value. For example, this counts a client's requests within a one-minute window:
1use laravel::cache;2use laravel::prelude::*;34let hits = cache::increment_or_add("hits:203.0.113.7", 1, 1.minute()).await?;1use laravel::cache;2use laravel::prelude::*;34let hits = cache::increment_or_add("hits:203.0.113.7", 1, 1.minute()).await?;
cache::increment and cache::decrement adjust an existing counter without changing its expiration, returning None if the key does not exist:
1let visits: Option<i64> = cache::increment("visits", 1).await?;2let remaining: Option<i64> = cache::decrement("credits", 1).await?;1let visits: Option<i64> = cache::increment("visits", 1).await?;2let remaining: Option<i64> = cache::decrement("credits", 1).await?;
Removing items
Use cache::forget to remove a single key, or cache::flush to clear every entry in the store:
1use laravel::cache;23cache::forget("user:42:name").await?;45cache::flush().await?;1use laravel::cache;23cache::forget("user:42:name").await?;45cache::flush().await?;
You may also flush the default store, or a specific store by name, using the cache:clear command:
1laravel cache:clear2laravel cache:clear reports1laravel cache:clear2laravel cache:clear reports
Each running process keeps a separate memory store, so cache:clear cannot clear the in-memory cache of a running web server. Restart the server to clear a memory store instead.
Flushing ignores CACHE_PREFIX. Flushing a database store empties the entire cache table, including entries written by other applications sharing that table.
Memoizing reads
When a single request reads the same cache key multiple times, such as a configuration value needed across several components, cache::memo() avoids redundant round trips to the store. It wraps the default store and keeps read results in memory for the remainder of the current request:
1use laravel::cache;23let cache = cache::memo()?;45let theme: Option<String> = cache.get("settings:theme").await?; // Reads the store...6let theme: Option<String> = cache.get("settings:theme").await?; // Served from memory...1use laravel::cache;23let cache = cache::memo()?;45let theme: Option<String> = cache.get("settings:theme").await?; // Reads the store...6let theme: Option<String> = cache.get("settings:theme").await?; // Served from memory...
To memoize another store, call .memo() on it, such as cache::store("reports")?.memo(). Writing or forgetting a key clears its memoized entry so the request always sees its own writes.
Atomic locks
Atomic locks allow you to coordinate distributed work so only one process executes a critical section at a time, such as generating an expensive report requested simultaneously by multiple users. Locks on the database and redis stores are shared across all processes and servers. Locks on the memory store only coordinate within a single process, and the discard store does not enforce locks.
Managing locks
Call cache::lock with a lock name and a maximum duration to hold the lock. Calling acquire attempts to claim the lock immediately and returns true if successful:
1use laravel::cache;2use laravel::prelude::*;34let lock = cache::lock("reports", 10.seconds())?;56if lock.acquire().await? {7 // Lock acquired for 10 seconds...89 lock.release().await?;10}1use laravel::cache;2use laravel::prelude::*;34let lock = cache::lock("reports", 10.seconds())?;56if lock.acquire().await? {7 // Lock acquired for 10 seconds...89 lock.release().await?;10}
Alternatively, pass a closure to get. Laravel acquires the lock, runs your closure, and automatically releases the lock afterward, even if the closure returns an error. If another process already holds the lock, get returns None without running the closure:
1let sent: Option<()> = cache::lock("invoices", 2.minutes())?2 .get(async || {3 // Send the invoices...45 Ok(())6 })7 .await?;1let sent: Option<()> = cache::lock("invoices", 2.minutes())?2 .get(async || {3 // Send the invoices...45 Ok(())6 })7 .await?;
If the lock is unavailable, you may instruct Laravel to wait for a given number of seconds using block. If the lock cannot be acquired before the timeout expires, block fails with a LockTimeout error, which Laravel renders as a 423 Locked response if returned from a handler:
1let report: String = cache::lock("reports", 10.seconds())?2 .block(5.seconds())3 .get(async || {4 // Generate the report...56 Ok(String::from("..."))7 })8 .await?;1let report: String = cache::lock("reports", 10.seconds())?2 .block(5.seconds())3 .get(async || {4 // Generate the report...56 Ok(String::from("..."))7 })8 .await?;
To handle a timeout yourself, await block directly and check the error with is::<LockTimeout>():
1use laravel::cache::{self, LockTimeout};2use laravel::prelude::*;34let lock = cache::lock("reports", 10.seconds())?;56match lock.block(5.seconds()).await {7 Ok(()) => {8 // Lock acquired after waiting up to 5 seconds...910 lock.release().await?;11 }12 Err(error) if error.is::<LockTimeout>() => {13 // Unable to acquire the lock...14 }15 Err(error) => return Err(error),16}1use laravel::cache::{self, LockTimeout};2use laravel::prelude::*;34let lock = cache::lock("reports", 10.seconds())?;56match lock.block(5.seconds()).await {7 Ok(()) => {8 // Lock acquired after waiting up to 5 seconds...910 lock.release().await?;11 }12 Err(error) if error.is::<LockTimeout>() => {13 // Unable to acquire the lock...14 }15 Err(error) => return Err(error),16}
When protecting a database transaction with a lock, acquire the lock before starting the transaction so the lock is released only after the transaction commits.
Locks acquired via acquire or by awaiting block must be released explicitly with release. Dropping a lock or panicking does not release it, so it remains held until its duration expires. Choose a duration longer than the protected work, or refresh the lock as work progresses. Using get releases the lock automatically, even if the request is cancelled.
Managing locks across processes
Sometimes you need to acquire a lock in one process and release it in another, such as acquiring a lock in an HTTP handler and releasing it when a queued job completes. Pass the lock's owner token to the job:
1use laravel::cache;2use laravel::prelude::*;34use crate::jobs::ProcessPodcast;56pub async fn process(Params(podcast_id): Params<i64>) -> laravel::Result<Redirect> {7 let lock = cache::lock("processing", 2.minutes())?;89 if lock.acquire().await? {10 let owner = lock.owner().to_owned();1112 ProcessPodcast { podcast_id, owner }.dispatch().await?;13 }1415 Ok(Redirect::back())16}1use laravel::cache;2use laravel::prelude::*;34use crate::jobs::ProcessPodcast;56pub async fn process(Params(podcast_id): Params<i64>) -> laravel::Result<Redirect> {7 let lock = cache::lock("processing", 2.minutes())?;89 if lock.acquire().await? {10 let owner = lock.owner().to_owned();1112 ProcessPodcast { podcast_id, owner }.dispatch().await?;13 }1415 Ok(Redirect::back())16}
Inside the job, restore the lock with the owner token and release it:
1// src/jobs/process_podcast.rs2use laravel::cache;3use laravel::queue::{Queueable, job};45#[derive(Queueable)]6pub struct ProcessPodcast {7 pub podcast_id: i64,8 pub owner: String,9}1011#[job]12impl ProcessPodcast {13 async fn handle(self) -> laravel::Result<()> {14 // Process the podcast...1516 cache::restore_lock("processing", &self.owner)?.release().await?;1718 Ok(())19 }20}1// src/jobs/process_podcast.rs2use laravel::cache;3use laravel::queue::{Queueable, job};45#[derive(Queueable)]6pub struct ProcessPodcast {7 pub podcast_id: i64,8 pub owner: String,9}1011#[job]12impl ProcessPodcast {13 async fn handle(self) -> laravel::Result<()> {14 // Process the podcast...1516 cache::restore_lock("processing", &self.owner)?.release().await?;1718 Ok(())19 }20}
To release a lock regardless of its current owner, call force_release.
Refreshing locks
For long-running tasks, acquire a short-lived lock and extend it as work progresses rather than guessing an overly long duration up front. refresh resets the lock's expiration to its original duration from the current time, returning false if the lock has already expired or is held by another owner:
1use laravel::cache;2use laravel::prelude::*;34let lock = cache::lock("yearly-reports", 1.minute())?;56if lock.acquire().await? {7 for month in 1..=12 {8 // Generate the month's report...910 lock.refresh().await?;11 }1213 lock.release().await?;14}1use laravel::cache;2use laravel::prelude::*;34let lock = cache::lock("yearly-reports", 1.minute())?;56if lock.acquire().await? {7 for month in 1..=12 {8 // Generate the month's report...910 lock.refresh().await?;11 }1213 lock.release().await?;14}
Because a restored lock does not know its original duration, extend it with refresh_for(1.minute()) instead.
Logging
The cache writes a debug log line under the laravel::cache target for every key it reads, writes, or removes. Each entry includes the store name and unprefixed key, without logging cached values. Enable these logs by raising the laravel::cache log level:
1LOG_LEVEL=info,laravel::cache=debug1LOG_LEVEL=info,laravel::cache=debug
| Message | Written when |
|---|---|
Cache hit |
A read finds a value. |
Cache missed |
A read finds no value. |
Cache key written |
A value is stored. |
Cache key forgotten |
A key is removed. |
Cache flushed |
A store is flushed. |
Custom drivers
To store cached values in a backend without a built-in driver, such as Memcached, implement the laravel::cache::Store trait. Your driver only needs to store and retrieve encoded strings by key; Laravel handles JSON serialization, key prefixes, durations, and logging for you:
1use std::time::Duration;23use laravel::cache::Store;45pub struct MemcachedStore {6 pub server: String,7}89impl Store for MemcachedStore {10 async fn get(&self, key: &str) -> laravel::Result<Option<String>> {11 // Return the value stored under the key...12 todo!()13 }1415 async fn put(&self, key: &str, value: String, ttl: Duration) -> laravel::Result<()> {16 // Store the value under the key, and expire it after the TTL...17 todo!()18 }1920 async fn add(&self, key: &str, value: String, ttl: Duration) -> laravel::Result<bool> {21 // Store the value only if the key is missing, and return whether you stored it...22 todo!()23 }2425 async fn increment(&self, key: &str, by: i64) -> laravel::Result<Option<i64>> {26 // Add to an existing counter and return its new value, or `None` when the key is missing...27 todo!()28 }2930 async fn forget(&self, key: &str) -> laravel::Result<bool> {31 // Delete the key, and return whether it existed...32 todo!()33 }3435 async fn flush(&self) -> laravel::Result<()> {36 // Delete every key...37 todo!()38 }39}1use std::time::Duration;23use laravel::cache::Store;45pub struct MemcachedStore {6 pub server: String,7}89impl Store for MemcachedStore {10 async fn get(&self, key: &str) -> laravel::Result<Option<String>> {11 // Return the value stored under the key...12 todo!()13 }1415 async fn put(&self, key: &str, value: String, ttl: Duration) -> laravel::Result<()> {16 // Store the value under the key, and expire it after the TTL...17 todo!()18 }1920 async fn add(&self, key: &str, value: String, ttl: Duration) -> laravel::Result<bool> {21 // Store the value only if the key is missing, and return whether you stored it...22 todo!()23 }2425 async fn increment(&self, key: &str, by: i64) -> laravel::Result<Option<i64>> {26 // Add to an existing counter and return its new value, or `None` when the key is missing...27 todo!()28 }2930 async fn forget(&self, key: &str) -> laravel::Result<bool> {31 // Delete the key, and return whether it existed...32 todo!()33 }3435 async fn flush(&self) -> laravel::Result<()> {36 // Delete every key...37 todo!()38 }39}
Support for atomic locks and rate limiting is optional. To support locks on your custom store, also implement acquire_lock, release_lock, force_release_lock, refresh_lock, and lock_owner on Store. To support rate limiting, implement compare_and_swap:
1async fn acquire_lock(&self, name: &str, owner: &str, ttl: Duration) -> laravel::Result<bool> {2 // Acquire the lock for `owner` until `ttl` elapses if it is currently free...3 todo!()4}56async fn release_lock(&self, name: &str, owner: &str) -> laravel::Result<bool> {7 // Release the lock only if `owner` holds it...8 todo!()9}1011async fn force_release_lock(&self, name: &str) -> laravel::Result<()> {12 // Release the lock regardless of owner...13 todo!()14}1516async fn refresh_lock(&self, name: &str, owner: &str, ttl: Duration) -> laravel::Result<bool> {17 // Extend an unexpired lock held by `owner` to `ttl` from now...18 todo!()19}2021async fn lock_owner(&self, name: &str) -> laravel::Result<Option<String>> {22 // Return the current owner if the lock is held and unexpired...23 todo!()24}2526async fn compare_and_swap(27 &self,28 key: &str,29 current: Option<&str>,30 new: String,31 ttl: Duration,32) -> laravel::Result<bool> {33 // Atomically store `new` for `ttl` only if the current value matches `current`...34 todo!()35}1async fn acquire_lock(&self, name: &str, owner: &str, ttl: Duration) -> laravel::Result<bool> {2 // Acquire the lock for `owner` until `ttl` elapses if it is currently free...3 todo!()4}56async fn release_lock(&self, name: &str, owner: &str) -> laravel::Result<bool> {7 // Release the lock only if `owner` holds it...8 todo!()9}1011async fn force_release_lock(&self, name: &str) -> laravel::Result<()> {12 // Release the lock regardless of owner...13 todo!()14}1516async fn refresh_lock(&self, name: &str, owner: &str, ttl: Duration) -> laravel::Result<bool> {17 // Extend an unexpired lock held by `owner` to `ttl` from now...18 todo!()19}2021async fn lock_owner(&self, name: &str) -> laravel::Result<Option<String>> {22 // Return the current owner if the lock is held and unexpired...23 todo!()24}2526async fn compare_and_swap(27 &self,28 key: &str,29 current: Option<&str>,30 new: String,31 ttl: Duration,32) -> laravel::Result<bool> {33 // Atomically store `new` for `ttl` only if the current value matches `current`...34 todo!()35}
Register your driver by name in src/app.rs. Laravel invokes the factory lazily the first time your application accesses a store using that driver:
1Application::configure()2 .with_services(|app| {3 app.cache().extend("memcached", async |_app, _definition| {4 Ok(MemcachedStore {5 server: "127.0.0.1:11211".into(),6 })7 });8 })1Application::configure()2 .with_services(|app| {3 app.cache().extend("memcached", async |_app, _definition| {4 Ok(MemcachedStore {5 server: "127.0.0.1:11211".into(),6 })7 });8 })
A package can register its driver inside its service provider's register method. Next, define a store referencing your driver name and select it in .env:
1cache.add_store("memcached", StoreConfig::custom("memcached"));1cache.add_store("memcached", StoreConfig::custom("memcached"));
1CACHE_STORE=memcached1CACHE_STORE=memcached
If multiple stores share one driver with different settings, such as two Memcached servers, attach per-store settings with StoreConfig::custom("memcached").settings(..) and read them inside your factory via definition.settings::<T>().
Testing
Tests use the memory store by default, as described in configuring your tests. Each test runs with an isolated application and starts with an empty cache, so you can interact with the cache directly inside your tests:
1use laravel::cache;2use laravel::testing::prelude::*;34#[laravel::test]5async fn reports_are_cached(app: Application) -> laravel::Result<()> {6 app.get("/reports/monthly").await.assert_ok();78 assert!(cache::has("report:monthly").await?);910 Ok(())11}1use laravel::cache;2use laravel::testing::prelude::*;34#[laravel::test]5async fn reports_are_cached(app: Application) -> laravel::Result<()> {6 app.get("/reports/monthly").await.assert_ok();78 assert!(cache::has("report:monthly").await?);910 Ok(())11}
Cache expirations follow the application's clock, so you can test expiration behavior using time travel instead of sleeping.