How to Cache Queries in Laravel

How to Cache Queries in Laravel

How to Cache Queries in Laravel

Laravel's Cache facade supports many drivers (Redis, Memcached, file, database) and integrates cleanly with Eloquent.

Step 1 — Configure Cache Driver

# .env
CACHE_STORE=redis
REDIS_HOST=127.0.0.1
REDIS_PORT=6379

Step 2 — Cache a Query Result

use Illuminate\Support\Facades\Cache;

// remember() fetches from cache, or runs the closure and stores the result
$topics = Cache::remember('topics.all', now()->addHours(6), function () {
    return Topic::where('status', 0)->orderBy('name')->get();
});

Step 3 — Cache Forever and Forget

// Store indefinitely
Cache::forever('settings', Setting::all()->keyBy('key'));

// Invalidate when data changes
Cache::forget('settings');

// Or use tags (Redis/Memcached only)
Cache::tags(['settings'])->flush();

Step 4 — Invalidate in Observers

// app/Observers/TopicObserver.php
public function saved(Topic $topic): void
{
    Cache::forget('topics.all');
}

public function deleted(Topic $topic): void
{
    Cache::forget('topics.all');
}
All Comments