Laravel Cache

Cache LibraryPHPLaravelFrameworkRedisMemcachedFacade

GitHub Overview

laravel/framework

The Laravel Framework.

Stars33,844
Watchers958
Forks11,444
Created:January 10, 2013
Language:PHP
License:MIT License

Topics

frameworklaravelphp

Star History

laravel/framework Star History
Data as of: 7/19/2025, 09:31 AM

Cache Library

Laravel Cache

Overview

Laravel Cache is a caching system built into the Laravel PHP framework that allows you to operate multiple cache backends (Redis, Memcached, file, database, etc.) through a unified API.

Details

Laravel Cache is one of the core features of the Laravel framework, designed as a caching solution to improve application performance. It supports various cache drivers including Redis, Memcached, file-based, database, and array (memory), which can be easily switched through configuration files. It provides an intuitive API through the Cache facade, offering basic operations like get, put, forever, forget, increment, as well as high-level functions like remember and rememberForever. Tag-based caching enables batch operations on grouped data, simultaneous use of multiple stores, and custom driver implementation. Complete integration with the Laravel ecosystem enables automatic caching at various levels including Eloquent query caching, view caching, and route caching. It contributes to overall framework acceleration through artisan command cache management, configuration value caching, and session caching.

Pros and Cons

Pros

  • Unified API: Operate multiple cache backends with the same interface
  • Rich Drivers: Support for Redis, Memcached, file, DB, and array
  • Framework Integration: Complete integration with Laravel ecosystem
  • Facade Pattern: Concise and intuitive API design
  • Tag-based Caching: Efficient management of grouped caches
  • Artisan Commands: Easy cache management from command line
  • Rich Features: TTL, increment/decrement operations, conditional caching, etc.

Cons

  • Laravel Dependency: Cannot be used outside Laravel framework
  • PHP Only: Not available for languages other than PHP
  • Configuration Complexity: Complex configuration when using multiple stores
  • Performance: Slight overhead from facade usage
  • Debugging Difficulty: Cache-related issues can be difficult to debug

Official Links

Code Examples

Basic Configuration (config/cache.php)

<?php
// config/cache.php

return [
    // Default cache store
    'default' => env('CACHE_DRIVER', 'redis'),
    
    // Cache store configurations
    'stores' => [
        'redis' => [
            'driver' => 'redis',
            'connection' => 'cache',
            'lock_connection' => 'default',
        ],
        
        'memcached' => [
            'driver' => 'memcached',
            'persistent_id' => env('MEMCACHED_PERSISTENT_ID'),
            'sasl' => [
                env('MEMCACHED_USERNAME'),
                env('MEMCACHED_PASSWORD'),
            ],
            'options' => [
                // Memcached::OPT_CONNECT_TIMEOUT => 2000,
            ],
            'servers' => [
                [
                    'host' => env('MEMCACHED_HOST', '127.0.0.1'),
                    'port' => env('MEMCACHED_PORT', 11211),
                    'weight' => 100,
                ],
            ],
        ],
        
        'file' => [
            'driver' => 'file',
            'path' => storage_path('framework/cache/data'),
        ],
        
        'database' => [
            'driver' => 'database',
            'table' => 'cache',
            'connection' => null,
            'lock_connection' => null,
        ],
    ],
    
    // Cache key prefix
    'prefix' => env('CACHE_PREFIX', Str::slug(env('APP_NAME', 'laravel'), '_').'_cache'),
];

Basic Cache Operations

<?php

use Illuminate\Support\Facades\Cache;

class CacheExampleController extends Controller
{
    public function basicOperations()
    {
        // Store data
        Cache::put('key', 'value', 600); // Valid for 600 seconds
        Cache::put('user:123', ['name' => 'John', 'email' => '[email protected]'], now()->addHours(1));
        
        // Retrieve data
        $value = Cache::get('key');
        $user = Cache::get('user:123');
        
        // Retrieve with default value
        $setting = Cache::get('app_setting', 'default_value');
        
        // Check data existence
        if (Cache::has('key')) {
            echo "Key exists in cache";
        }
        
        // Delete data
        Cache::forget('key');
        
        // Clear all cache
        Cache::flush();
        
        // Permanent cache (no expiration)
        Cache::forever('permanent_data', 'important_value');
        
        // Increment/decrement numbers
        Cache::increment('page_views');
        Cache::decrement('remaining_items', 5);
        
        return response()->json(['status' => 'Cache operations completed']);
    }
}

Using remember/rememberForever

<?php

use Illuminate\Support\Facades\Cache;
use App\Models\User;

class UserService
{
    public function getUserProfile($userId)
    {
        // Get from cache, fetch from DB and cache if not exists
        return Cache::remember("user_profile_{$userId}", 3600, function () use ($userId) {
            return User::with(['profile', 'preferences'])
                       ->find($userId)
                       ->toArray();
        });
    }
    
    public function getPopularPosts()
    {
        // Permanent cache version
        return Cache::rememberForever('popular_posts', function () {
            return Post::where('views', '>', 1000)
                      ->orderBy('views', 'desc')
                      ->take(10)
                      ->get();
        });
    }
    
    public function getUserSettings($userId)
    {
        $cacheKey = "user_settings_{$userId}";
        
        // pull: Get from cache and immediately delete
        return Cache::pull($cacheKey, function () use ($userId) {
            return UserSetting::where('user_id', $userId)->first();
        });
    }
    
    public function getApiData($endpoint)
    {
        return Cache::remember("api_data_{$endpoint}", 1800, function () use ($endpoint) {
            // Fetch data from external API
            $response = Http::get("https://api.example.com/{$endpoint}");
            return $response->json();
        });
    }
}

Using Multiple Stores

<?php

use Illuminate\Support\Facades\Cache;

class MultiStoreService
{
    public function demonstrateMultipleStores()
    {
        // Use default store
        Cache::put('default_key', 'default_value', 600);
        
        // Use specific stores
        Cache::store('redis')->put('redis_key', 'redis_value', 600);
        Cache::store('memcached')->put('memcached_key', 'memcached_value', 600);
        Cache::store('file')->put('file_key', 'file_value', 600);
        
        // Retrieve data from each store
        $defaultValue = Cache::get('default_key');
        $redisValue = Cache::store('redis')->get('redis_key');
        $memcachedValue = Cache::store('memcached')->get('memcached_key');
        $fileValue = Cache::store('file')->get('file_key');
        
        return [
            'default' => $defaultValue,
            'redis' => $redisValue,
            'memcached' => $memcachedValue,
            'file' => $fileValue,
        ];
    }
    
    public function sessionCaching()
    {
        // Use session-specific cache store
        $sessionStore = Cache::store('session');
        $sessionStore->put('user_cart', ['item1', 'item2'], 7200);
        
        return $sessionStore->get('user_cart', []);
    }
}

Tagged Cache

<?php

use Illuminate\Support\Facades\Cache;

class TaggedCacheService
{
    public function useTaggedCache()
    {
        // Store tagged cache
        Cache::tags(['users', 'posts'])->put('user_posts_123', $postsData, 3600);
        Cache::tags(['users'])->put('user_profile_123', $profileData, 3600);
        Cache::tags(['posts'])->put('recent_posts', $recentPosts, 1800);
        
        // Retrieve tagged cache
        $userPosts = Cache::tags(['users', 'posts'])->get('user_posts_123');
        $userProfile = Cache::tags(['users'])->get('user_profile_123');
        
        // Flush all cache with specific tags
        Cache::tags(['posts'])->flush(); // Delete all post-related cache
        Cache::tags(['users'])->flush(); // Delete all user-related cache
        
        return [
            'user_posts' => $userPosts,
            'user_profile' => $userProfile,
        ];
    }
    
    public function cacheInvalidation($userId)
    {
        // Batch delete user-related cache
        Cache::tags(['users', "user_{$userId}"])->flush();
        
        // Partial tag cache deletion
        Cache::tags(['products', 'category_electronics'])->flush();
    }
}

Eloquent Model Cache Integration

<?php

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Cache;

class Product extends Model
{
    protected $fillable = ['name', 'price', 'category_id', 'description'];
    
    // Cache management with model events
    protected static function boot()
    {
        parent::boot();
        
        static::saved(function ($product) {
            // Clear cache on product update
            Cache::tags(['products', "product_{$product->id}"])->flush();
            Cache::forget("category_products_{$product->category_id}");
        });
        
        static::deleted(function ($product) {
            // Clear cache on product deletion
            Cache::tags(['products', "product_{$product->id}"])->flush();
        });
    }
    
    // Cached scope
    public function scopeCached($query, $key, $minutes = 60)
    {
        return Cache::remember($key, $minutes * 60, function () use ($query) {
            return $query->get();
        });
    }
    
    // Cached retrieval by category
    public static function getCachedByCategory($categoryId)
    {
        return Cache::remember("category_products_{$categoryId}", 3600, function () use ($categoryId) {
            return static::where('category_id', $categoryId)
                        ->with('category')
                        ->orderBy('created_at', 'desc')
                        ->get();
        });
    }
}

class ProductController extends Controller
{
    public function index()
    {
        // Cached product list
        $products = Cache::remember('all_products', 3600, function () {
            return Product::with('category')->paginate(20);
        });
        
        return view('products.index', compact('products'));
    }
    
    public function show($id)
    {
        $product = Cache::remember("product_detail_{$id}", 7200, function () use ($id) {
            return Product::with(['category', 'reviews'])->findOrFail($id);
        });
        
        return view('products.show', compact('product'));
    }
}

Custom Cache Driver

<?php

use Illuminate\Cache\CacheManager;
use Illuminate\Support\ServiceProvider;

class CustomCacheServiceProvider extends ServiceProvider
{
    public function register()
    {
        $this->app->resolving('cache', function (CacheManager $cache) {
            $cache->extend('custom', function ($app, $config) {
                return new CustomCacheStore($config);
            });
        });
    }
}

class CustomCacheStore implements \Illuminate\Contracts\Cache\Store
{
    protected $config;
    
    public function __construct($config)
    {
        $this->config = $config;
    }
    
    public function get($key)
    {
        // Custom retrieval logic
        return $this->retrieveFromCustomSource($key);
    }
    
    public function put($key, $value, $seconds)
    {
        // Custom storage logic
        return $this->storeToCustomSource($key, $value, $seconds);
    }
    
    public function forget($key)
    {
        // Custom deletion logic
        return $this->deleteFromCustomSource($key);
    }
    
    public function flush()
    {
        // Custom flush logic
        return $this->clearCustomSource();
    }
    
    public function getPrefix()
    {
        return $this->config['prefix'] ?? '';
    }
    
    // Implementation of other required methods...
}

Artisan Commands and Cache Management

# Clear cache
php artisan cache:clear

# Configuration cache
php artisan config:cache
php artisan config:clear

# Route cache
php artisan route:cache
php artisan route:clear

# View cache
php artisan view:cache
php artisan view:clear

# Optimize all caches
php artisan optimize
php artisan optimize:clear