Skip to content
Tutorials Center
My learning

Topics

Lesson 43 of 67 ยท Caching and Performance

Caching in Laravel

Learn Laravel caching - cache stores, Cache::remember, TTLs, tags, atomic locks, invalidation on write, and the rate limiter, with runnable PHP stand-ins.

Some work is expensive and rarely changes: a dashboard query that scans a million rows, a list of countries, the response from a slow third-party API. Laravel gives you one small, consistent API for storing the result once and reusing it. You write Cache::get() or Cache::remember(), and a configuration setting decides whether the data lives in memory, in your database, in files or in Redis.

In this lesson you will learn the cache API, how to pick a store, how to keep cached data fresh, and how to use atomic locks and the rate limiter, which are built on the same cache. The framework code is shown in read-only blocks, because Laravel itself cannot run on this site. The runnable examples are plain-PHP stand-ins that behave like the real thing, so you can see exactly what happens on each call. For the general theory (cache-aside, TTLs, stampedes) read caching strategies in PHP first or after.

Choosing a cache store

The store is chosen with the CACHE_STORE variable in .env and configured in config/cache.php. Your code never changes when the store does.

Store Where data lives Good for
array PHP memory of the current process Tests (it vanishes at the end of the request)
file Files in storage/framework/cache Small sites, one server
database A cache table Simple setups; the default in new projects
redis A Redis server Production, many servers, tags, fast locks
memcached A Memcached server Production, many servers
null Nowhere (every get misses) Turning the cache off while debugging

For production, use Redis when you can. Tags (below) only work with the redis and memcached stores, and Redis is also the usual home for queues and sessions. You can configure several stores and pick one at runtime with Cache::store('redis')->get(...).

The basic API

PHP
use Illuminate\Support\Facades\Cache;

Cache::put('site:name', 'Tutorials', 600);      // seconds, or a DateTimeInterface
Cache::put('site:name', 'Tutorials', now()->addMinutes(10));

$name = Cache::get('site:name');                // null when missing
$name = Cache::get('site:name', 'Default');     // default value
$name = Cache::get('site:name', fn () => expensiveDefault());

Cache::has('site:name');                        // true when present and not null
Cache::add('lock-key', 1, 60);                  // stores only if the key is missing
Cache::forever('settings', $settings);          // no expiry (still evictable)
Cache::forget('site:name');                     // delete one key
Cache::pull('site:name');                       // get and delete
Cache::increment('visits');                     // atomic counter on most stores

A value stored with put() is serialized, so you can cache arrays and most objects. Do not cache Eloquent models or huge collections carelessly: a small array of exactly the fields you need is cheaper to store and safer when the class changes after a deploy.

remember: the pattern you will use most

Cache::remember() is the cache-aside pattern in one call: return the cached value if it exists, otherwise run the closure, store the result and return it.

PHP
$topPosts = Cache::remember('posts:top', now()->addMinutes(10), function () {
    return Post::query()
        ->withCount('comments')
        ->orderByDesc('comments_count')
        ->limit(10)
        ->get(['id', 'title', 'slug']);
});

$countries = Cache::rememberForever('countries', fn () => Country::all(['code', 'name']));

Laravel also has Cache::flexible(), which implements "stale while revalidate": it serves a slightly stale value instantly and refreshes it in the background after the request. Use it for expensive, popular keys where a brief delay in freshness is fine. Check the cache docs for the exact signature of your version before using it.

flowchart LR
    R["Cache::remember('posts:top', ttl, fn)"] --> H{"Key in store?"}
    H -- "yes" --> V["Return stored value"]
    H -- "no" --> C["Run the closure<br/>(database query)"]
    C --> S["Store with TTL"]
    S --> V

remember checks the store first and only runs your closure on a miss.

The stand-in below behaves like this part of the API, with a fake clock so the TTL is deterministic.

PHP A cache store with TTL, remember and add

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Keeping the cache correct

The famous joke says there are two hard problems in computer science: cache invalidation and naming things. Two habits cover most real cases.

1. Always set a TTL. If you forget to invalidate, the data fixes itself when the TTL ends. Use forever only for data that you also delete explicitly.

2. Delete (or refresh) on write. When the underlying data changes, remove the key in the same code path. Model events and observers are a natural place:

PHP
class PostObserver
{
    public function saved(Post $post): void
    {
        Cache::forget('posts:top');
        Cache::forget("posts:{$post->id}");
    }

    public function deleted(Post $post): void
    {
        $this->saved($post);
    }
}

Put every input that changes the result into the key: "dashboard:{$user->id}:{$locale}", never just "dashboard". A shared key for per-user data is a data leak.

Tags

When one change must clear many related keys, tag them. Tags are only available on Redis and Memcached.

PHP
Cache::tags(['posts', 'homepage'])->put('latest', $latest, 600);
Cache::tags(['posts'])->remember("author:{$id}", 600, fn () => $this->load($id));

Cache::tags(['posts'])->flush();   // clears every entry tagged "posts"

Reading a tagged entry needs the same tags you wrote it with. The stand-in below shows the idea: each tag remembers its keys, and flushing a tag deletes them.

PHP Tagged keys and an atomic lock stand-in

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Atomic locks

If two workers start the same expensive job at the same moment, you may do the work twice or corrupt data. A lock lets only one proceed. Laravel's locks live in the cache store and are atomic, which means the check and the claim happen as one step (a plain has() followed by put() would have a race in between).

PHP
$lock = Cache::lock('generate-report', 10);       // held for at most 10 seconds

if ($lock->get()) {
    try {
        generateReport();
    } finally {
        $lock->release();
    }
}

// or with a closure: the lock is released for you
Cache::lock('generate-report', 10)->get(fn () => generateReport());

// wait up to 5 seconds for the lock instead of giving up at once
Cache::lock('generate-report', 10)->block(5, fn () => generateReport());

The lock needs a store that supports it (Redis, Memcached, database, file and array do, among others). The expiry protects you when a process crashes while holding the lock.

The rate limiter

The rate limiter counts hits per key and per time window, using the cache. You will meet it most often through the throttle middleware, with limiters defined in AppServiceProvider::boot():

PHP
use Illuminate\Cache\RateLimiting\Limit;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\RateLimiter;

RateLimiter::for('api', function (Request $request) {
    return Limit::perMinute(60)->by($request->user()?->id ?: $request->ip());
});

// routes/api.php
Route::middleware('throttle:api')->group(function () {
    // ...
});

You can also call it by hand for any action, for example to protect a contact form:

PHP
$executed = RateLimiter::attempt(
    key: 'send-message:'.$request->ip(),
    maxAttempts: 3,
    callback: fn () => $this->sendMessage($request),
    decaySeconds: 60,
);

if (! $executed) {
    return back()->withErrors(['message' => 'Too many messages. Try again later.']);
}

When a request is throttled, Laravel answers with 429 Too Many Requests and a Retry-After header.

Cache commands

Terminal
php artisan cache:clear               # flush the default store
php artisan cache:forget posts:top    # delete one key
php artisan optimize:clear            # clear config, route, view and event caches too

Run cache:clear carefully on a shared Redis: it flushes the whole configured store. Use a CACHE_PREFIX per application so that applications do not collide.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does Cache::remember('key', 600, fn () => compute()) do on a cache miss?

    remember is cache-aside in one call. It returns the stored value on a hit and only runs the closure on a miss, storing the result with the given TTL.
  2. 2. Why should a per-user dashboard key include the user id?

    A key must contain every input that changes the result. A shared key for per-user data leaks one user's data to others.
  3. 3. Which stores support cache tags?

    Tags need a store that can keep sets of keys efficiently. The file and database stores do not support them.
  4. 4. Why is Cache::lock() better than checking has() and then calling put()?

    With has() then put(), two processes can both see the key as free before either stores it. An atomic lock removes that gap.
  5. 5. What does Laravel return when a throttle middleware limit is exceeded?

    The throttle middleware answers with 429, usually with a Retry-After header telling the client when to try again.

Summary

  • Choose the store with CACHE_STORE; use Redis in production, array in tests.
  • Cache::remember() is the workhorse: return the stored value or compute and store it.
  • Always set a TTL, delete or refresh on write, and put every input in the key.
  • Tags (Redis and Memcached only) clear groups of related keys.
  • Cache::lock() gives atomic locks; RateLimiter and the throttle middleware count hits in the cache.

Next: Performance and Optimization