🏠 Home 👤 About ⚡ Skills 💼 Portfolio 📦 Packages 📝 Blog ✉ Contact ✉ Contact Now
All Articles

Laravel Caching Strategies That Survive Real Traffic

Caching is easy to add and hard to invalidate. Here are the patterns that hold up — and the one mistake that serves stale data to everyone for an hour.

Junaid Ali 2 min read 0 views

Caching turns an expensive operation into a cheap one. It also turns a correctness problem into a much more confusing correctness problem, because the wrong answer is now served fast and consistently.

The Bread-and-Butter Pattern

public static function allCached(): array
{
    return Cache::remember('site_settings', 3600, function () {
        return static::pluck('value', 'key')->toArray();
    });
}

One database query per hour instead of one per request. On a settings table read on every page, that is a meaningful win.

Invalidate on Write, Not on a Timer

The mistake I see most: caching for an hour and relying on expiry. An admin updates a setting, sees no change, updates it again, and files a bug.

public static function set(string $key, mixed $value): void
{
    static::updateOrCreate(['key' => $key], ['value' => $value]);
    Cache::forget('site_settings');
}

Better still, hook model events so it cannot be forgotten:

static::saved(fn () => Cache::forget('site_settings'));
static::deleted(fn () => Cache::forget('site_settings'));

Cache Keys Must Include Every Variable

A key like posts_page that ignores the page number will serve page one to everybody. Build keys from every input that changes the result:

$key = "posts:{$categoryId}:page:{$page}";

Tags for Grouped Invalidation

With Redis or Memcached you can clear a whole group at once — useful when one write affects many cached views.

Cache::tags(['posts'])->remember($key, 600, $callback);
Cache::tags(['posts'])->flush();

Do Not Forget the Framework Caches

php artisan config:cache
php artisan route:cache
php artisan view:cache

Run these on deploy, and remember that config:cache means env() outside config files returns null. That one has caught a lot of people.

Know What Not to Cache

Anything user-specific in a shared key. Anything where stale data causes a real problem — stock levels, balances, permissions. Cache the expensive and stable; leave the cheap and volatile alone.

Tagged Laravel Caching Performance Redis
Share this article

Want this built properly?

I take on a small number of projects at a time so each one gets real attention.

WhatsApp Teams LinkedIn Facebook GitHub