What does the `Cache::touch(...)` method do in Laravel 13?

In Laravel 13, the Cache::touch(...) method is a new addition designed to refresh the expiration time (TTL) of an existing cache item without reading or rewriting its stored value. This addresses a long-standing inefficiency: previously, extending a cache item is life required a get followed by a put, which meant fetching the serialized payload, deserializing it, and writing it back—wasteful on high-traffic systems where you only wanted to bump the timer.

Why It Matters?

Consider a scenario where you cache a user is dashboard metrics for 10 minutes, but every time the user interacts with the dashboard, you want to reset that 10-minute window. Before Laravel 13, you d do:

$value = Cache::get( dashboard: .$userId);
if ($value !== null) {
   Cache::put( dashboard: .$userId, $value, 600);
}

This works, but it incurs a read and a write. With Cache::touch(), the operation becomes a single, driver-optimized command:

Cache::touch( dashboard: .$userId, 600);

Under the hood, Laravel translates this into native store commands—EXPIRE for Redis, touch for Memcached, and a direct UPDATE on the expiration column for the database driver—so the value itself is never transferred over the wire.

Practical Example

A common use case is sliding expiration for API tokens or session-like data:

use IlluminateSupportFacadesCache;

// Store a token with a 30-minute TTL
Cache::put( api_token: .$token, $userId, now()->addMinutes(30));

// Later, when the token is used, extend its life without re-reading the value
if (Cache::has( api_token: .$token)) {
   Cache::touch( api_token: .$token, now()->addMinutes(30));
}

You can pass the TTL as seconds (integer) or as a DateTimeInterface via now()->addMinutes(...).

15 Views