Laravel
Caching
Laravel's unified caching API supports multiple backends — file, database, Redis, Memcached — letting you store and retrieve expensive computations or query results with a single consistent interface.
Cache Driver Config: Set the default cache store in
.env. Common options: file (default), redis, memcached, database, array (testing only)..env
ENV
CACHE_DRIVER=file # Default — stored in storage/framework/cache
CACHE_DRIVER=redis # Fast in-memory; recommended for production
CACHE_DRIVER=database # Stored in cache table
CACHE_DRIVER=memcached # Memcached server
# Redis config (if using redis driver)
REDIS_HOST=127.0.0.1
REDIS_PASSWORD=null
REDIS_PORT=6379
REDIS_CACHE_DB=1 # Use a separate DB index for cache
Cache::put / get / has / forget: The core cache operations — store a value, retrieve it, check existence, or remove it.
app/Http/Controllers/ExampleController.php
PHP
use Illuminate\Support\Facades\Cache;
// Store a value for 10 minutes
Cache::put('user_count', 1234, now()->addMinutes(10));
// Store forever (no expiry)
Cache::forever('settings', ['theme' => 'dark']);
// Retrieve a value (returns null if not found)
$count = Cache::get('user_count');
// Retrieve with a default fallback
$count = Cache::get('user_count', 0);
// Check if key exists
if (Cache::has('user_count')) {
// ...
}
// Remove a single key
Cache::forget('user_count');
// Retrieve and delete in one step
$value = Cache::pull('one_time_token');
Cache::remember: The most useful pattern — retrieve from cache if available, otherwise run the closure and store the result. Keeps your code clean.
app/Http/Controllers/ProductController.php
PHP
use Illuminate\Support\Facades\Cache;
use App\Models\Product;
// Cache for 30 minutes; if key exists return it, else run closure
$products = Cache::remember('products.featured', now()->addMinutes(30), function () {
return Product::where('is_featured', true)
->with('category')
->get();
});
// Remember forever
$categories = Cache::rememberForever('categories.all', function () {
return Category::orderBy('name')->get();
});
// Per-user cache key
$userId = auth()->id();
$userProfile = Cache::remember("user.{$userId}.profile", now()->addHour(), function () use ($userId) {
return User::with(['roles', 'permissions'])->find($userId);
});
Cache Tags: Tags let you group related cache items and flush them together. Only supported by
redis and memcached drivers.app/Services/ProductService.php
PHP
use Illuminate\Support\Facades\Cache;
// Store items with tags
Cache::tags(['products', 'featured'])
->put('products.featured', $products, now()->addMinutes(30));
Cache::tags(['products', 'all'])
->put('products.all', $allProducts, now()->addHour());
// Retrieve tagged item
$featured = Cache::tags(['products', 'featured'])->get('products.featured');
// Flush ALL items with the 'products' tag at once
// (e.g., call after any product create/update/delete)
Cache::tags(['products'])->flush();
// Usage in observer or model event
class ProductObserver
{
public function saved(Product $product): void
{
Cache::tags(['products'])->flush();
}
}
Redis Setup: Install the Predis or PhpRedis client. Redis is the recommended driver for production — fast, supports tags, pub/sub, and shared cache across servers.
terminal
BASH
# Install Predis (pure PHP, easy setup)
composer require predis/predis
# Or enable the phpredis PHP extension (faster)
# Add to php.ini: extension=redis
# Test Redis connection
php artisan tinker
>>> Cache::store('redis')->put('test', 'hello', 60)
>>> Cache::store('redis')->get('test')
config/database.php (redis section)
PHP
'redis' => [
'client' => env('REDIS_CLIENT', 'predis'),
'default' => [
'host' => env('REDIS_HOST', '127.0.0.1'),
'password' => env('REDIS_PASSWORD', null),
'port' => env('REDIS_PORT', 6379),
'database' => env('REDIS_DB', 0),
],
// Separate database index for cache to isolate cache keys
'cache' => [
'host' => env('REDIS_HOST', '127.0.0.1'),
'password' => env('REDIS_PASSWORD', null),
'port' => env('REDIS_PORT', 6379),
'database' => env('REDIS_CACHE_DB', 1),
],
],
Caching Query Results: Cache expensive Eloquent queries to avoid hitting the database on every request. Invalidate the cache when underlying data changes.
app/Services/DashboardService.php
PHP
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
class DashboardService
{
public function getStats(): array
{
return Cache::remember('dashboard.stats', now()->addMinutes(5), function () {
return [
'total_users' => User::count(),
'total_orders' => Order::where('status', 'completed')->count(),
'revenue_today' => Order::whereDate('created_at', today())->sum('total'),
'top_products' => DB::table('order_items')
->select('product_id', DB::raw('SUM(quantity) as sold'))
->groupBy('product_id')
->orderByDesc('sold')
->limit(5)
->get(),
];
});
}
public function invalidate(): void
{
Cache::forget('dashboard.stats');
}
}
View / Fragment Caching Concept: Laravel doesn't have built-in view caching in Blade, but you can cache rendered HTML strings or partial data and output them in your views.
app/Http/Controllers/HomeController.php
PHP
// Cache the rendered HTML of a Blade partial
$html = Cache::remember('homepage.sidebar', now()->addHour(), function () {
$categories = Category::withCount('products')->orderBy('name')->get();
return view('partials.sidebar', compact('categories'))->render();
});
return view('home', compact('html'));
resources/views/home.blade.php
HTML
{{-- Render cached HTML — use {!! !!} to avoid double-escaping --}}
{!! $html !!}
Cache Clearing Artisan Commands: Use these commands to clear application cache, config cache, route cache, and compiled views during development and deployment.
terminal – cache management
BASH
# Clear application cache (Cache::put values)
php artisan cache:clear
# Clear config cache (re-reads config files)
php artisan config:clear
# Clear route cache
php artisan route:clear
# Clear compiled view cache (Blade templates)
php artisan view:clear
# Clear event cache
php artisan event:clear
# Clear ALL caches in one command
php artisan optimize:clear
# Re-cache for production (faster boot)
php artisan config:cache
php artisan route:cache
php artisan view:cache
php artisan optimize # Runs config:cache + route:cache + event:cache