Cache
| Remember forever-ish | |
| Forget keys | |
| Tags note | |
| Drivers note |
Remember forever-ish
Remember runs the slow code once and stores the result under a key. Later calls read the stored value until the seconds run out.
Wrap reports, counters, and other slow reads the same way, with the Cache facade imported at the top.
use Illuminate\Support\Facades\Cache; $stats = Cache::remember("stats", 3600, function () { return Stats::build(); });
Forget keys
Cached values go stale when source data changes. Forget one key right after the matching update, so the next read rebuilds fresh data.
Flush wipes the whole store and fits deploys more than daily work, so prefer forget for single keys.
Cache::forget("stats"); Cache::flush();
Tags note
Tags group related keys so one call clears the whole group. Tag order stats with the orders tag, then flush only that tag after an order changes.
Not every driver supports tags, so confirm support before relying on them in code.
Cache::tags(["orders"])->remember("stats", 3600, function () { return Stats::build(); }); Cache::tags(["orders"])->flush();
Drivers note
The driver decides where cached values live. File suits small apps, array resets on every request and fits tests, while Redis and Memcached fit shared servers.
Pick the store in the env file and keep the code unchanged across drivers.
CACHE_STORE=file
Next: Sessions in Laravel
Article author: Arthur Isaev