LARAVEL

Laravel Cache Optimization: Complete Guide

March 10, 2024 18 min read

Introduction

Caching is essential for Laravel application performance. This guide covers various caching strategies, from basic file caching to advanced Redis implementations.

Cache Drivers

Available Drivers

// config/cache.php
'default' => env('CACHE_DRIVER', 'redis'),

'drivers' => [
    'file' => [
        'driver' => 'file',
        'path' => storage_path('framework/cache/data'),
    ],
    
    'redis' => [
        'driver' => 'redis',
        'connection' => 'cache',
    ],
    
    'memcached' => [
        'driver' => 'memcached',
        'persistent_id' => env('MEMCACHED_PERSISTENT_ID'),
        'sasl' => [
            env('MEMCACHED_USERNAME'),
            env('MEMCACHED_PASSWORD'),
        ],
        'options' => [
            // Memcached options
        ],
        'servers' => [
            [
                'host' => env('MEMCACHED_HOST', '127.0.0.1'),
                'port' => env('MEMCACHED_PORT', 11211),
                'weight' => 100,
            ],
        ],
    ],
    
    'dynamodb' => [
        'driver' => 'dynamodb',
        'key' => env('AWS_ACCESS_KEY_ID'),
        'secret' => env('AWS_SECRET_ACCESS_KEY'),
        'region' => env('AWS_DEFAULT_REGION', 'us-east-1'),
        'table' => env('DYNAMODB_CACHE_TABLE', 'cache'),
    ],
],

Basic Cache Usage

Storing Data

// Store for specified minutes
Cache::put('key', 'value', 60);

// Store forever
Cache::forever('key', 'value');

// Store with callback (remember pattern)
$users = Cache::remember('users', 60, function () {
    return User::all();
});

// Remember with callback
$users = Cache::rememberForever('users', function () {
    return User::all();
});

Retrieving Data

// Simple retrieval
$value = Cache::get('key');

// With default
$value = Cache::get('key', 'default');

// Pull and delete
$value = Cache::pull('key');

// Check if exists
if (Cache::has('key')) {
    // ...
}

Deleting Data

// Delete specific key
Cache::forget('key');

// Delete multiple keys
Cache::forget(['key1', 'key2']);

// Clear all cache
Cache::flush();

Cache Tags

Using Tags

// Store with tags
Cache::tags(['users', 'authors'])->put('user_1', $user, 60);
Cache::tags(['posts', 'recent'])->put('post_1', $post, 60);

// Retrieve tagged cache
$user = Cache::tags('users')->get('user_1');

// Flush tagged cache
Cache::tags('users')->flush();
Cache::tags(['users', 'posts'])->flush();

Tag Use Cases

// Cache user data by tag
Cache::tags(['user_'.$userId])->put('profile', $profile, 3600);
Cache::tags(['user_'.$userId])->put('settings', $settings, 3600);

// Flush all data for specific user
Cache::tags('user_'.$userId)->flush();

Redis Caching

Installation

composer require predis/predis
# or
pecl install redis

Configuration

// config/database.php
'redis' => [
    'client' => 'predis', // or 'phpredis'
    
    'options' => [
        'cluster' => 'redis',
        'prefix' => 'laravel_',
    ],
    
    'default' => [
        'host' => env('REDIS_HOST', '127.0.0.1'),
        'password' => env('REDIS_PASSWORD'),
        'port' => env('REDIS_PORT', 6379),
        'database' => env('REDIS_DB', 0),
    ],
    
    'cache' => [
        'host' => env('REDIS_HOST', '127.0.0.1'),
        'password' => env('REDIS_PASSWORD'),
        'port' => env('REDIS_PORT', 6379),
        'database' => env('REDIS_CACHE_DB', 1),
    ],
],

Redis Commands

// Direct Redis access
Redis::get('key');
Redis::set('key', 'value');
Redis::incr('counter');

// Cache + Redis
Cache::store('redis')->put('key', 'value', 60);

HTTP Caching

Route Cache

// Cache routes
php artisan route:cache

// Clear route cache
php artisan route:clear

Response Caching

// Using Cache-Control headers
Route::get('/api/users', function () {
    return response()
        ->json(User::all())
        ->header('Cache-Control', 'public, max-age=3600');
});

// Using middleware
Route::middleware('cache.headers:public;max_age=3600')->group(function () {
    Route::get('/api/users', function () {
        return User::all();
    });
});

Best Practices

  • Use appropriate TTL - Set expiration times based on data volatility
  • Implement cache warming - Pre-populate cache on application start
  • Monitor cache hit rate - Track cache performance
  • Use cache versioning - Invalidate cache when data structure changes
  • Implement graceful degradation - Fallback when cache is unavailable
  • Separate cache stores - Use different stores for different data types

Summary

Proper caching implementation can dramatically improve Laravel application performance. Choose the right cache driver and strategy based on your application's needs and scale.

For more Laravel tutorials, check out Laravel Performance Optimization and Laravel Queues & Jobs.