HomeLARAVELLaravel Cache – Complete Guide with Examples

Laravel Cache – Complete Guide with Examples

Caching is one of the best ways to speed up your Laravel application. Some operations, like fetching large datasets or running complex calculations, can be CPU-heavy or time-consuming. Instead of running them every time, Laravel allows you to store results temporarily in a fast storage system like Redis or Memcached — and serve them instantly.


1. Why Use Cache in Laravel?

  • Improved speed – Serve data instantly without re-processing.
  • Reduced database load – Fewer queries mean better performance.
  • Scalable – Handles high traffic more efficiently.
  • Flexible drivers – Supports Redis, Memcached, Database, DynamoDB, MongoDB, etc.

2. Laravel Cache Configuration

Laravel’s cache configuration is in:

config/cache.php

Here you can:

  • Set default cache driver
  • Configure multiple stores
  • Enable/disable cache events

Supported Drivers:

  • file – Stores data in files (default for local dev)
  • database – Stores in a DB table
  • memcached – Uses Memcached server
  • redis – Uses Redis
  • dynamodb – AWS DynamoDB table
  • array – In-memory (for tests)
  • null – No caching (disables cache)

3. Driver Setup

Database Cache

php artisan make:cache-table
php artisan migrate

Memcached

  • Install PECL Memcached extension
  • Configure in config/cache.php:
'memcached' => [
    'servers' => [
        ['host' => '127.0.0.1', 'port' => 11211, 'weight' => 100],
    ],
],

Redis

  • Install:
composer require predis/predis
  • Or enable PhpRedis extension
  • Configure in config/database.php → Redis section.

4. Basic Cache Usage

Storing Data

Cache::put('key', 'value', 600); // store for 10 minutes

Retrieving Data

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

Check if Key Exists

if (Cache::has('key')) { ... }

Retrieve and Store if Missing

$users = Cache::remember('users', 600, function () {
    return DB::table('users')->get();
});

Store Forever

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

Remove Item

Cache::forget('key');

5. Advanced Features

Stale While Revalidate

Serve slightly old data while recalculating fresh values:

$users = Cache::flexible('users', [5, 10], function () {
    return DB::table('users')->get();
});

Atomic Locks

Prevent race conditions:

Cache::lock('process', 10)->block(5, function () {
    // Only one process runs here
});

Memoized Cache

Avoid multiple cache hits in the same request:

$value = Cache::memo()->get('key');

6. Cache Helper Function

cache(['key' => 'value'], 600); // store
$value = cache('key'); // retrieve

7. Pro Tips

✅ Use tags if you want to clear related caches together
✅ For large apps, prefer Redis for speed
✅ Monitor cache size to avoid memory overflow
✅ Use remember instead of get + put to simplify code


8. Summary Table of Cache Methods

MethodDescription
get()Retrieve item
put()Store item
remember()Retrieve or store if missing
forever()Store permanently
forget()Remove item
flush()Clear entire cache
increment()Increase integer value
decrement()Decrease integer value
has()Check existence
pull()Get and delete

Best Practices

  • Tag your caches – makes invalidation easier
  • ✅ Use remember instead of get + put
  • ✅ Avoid storing huge data objects
  • ✅ Always set expiry unless permanent
  • ✅ Clear cache during deployment if needed

Common Mistakes

❌ Forgetting to set expiry → stale data forever
❌ Overusing cache for tiny, cheap queries
❌ Not clearing cache after DB updates
❌ Using file cache in high-traffic environments


Real-World Use Cases

  • Caching homepage data to reduce DB hits
  • Storing API responses for external calls
  • Caching user permissions for fast checks
  • Locking background jobs to prevent duplication
  • Storing computed analytics results

Cache Events

Laravel emits events for cache actions:

  • CacheHit
  • CacheMissed
  • KeyWritten
  • KeyForgotten
  • CacheFlushed

You can listen to these to log or debug cache usage.


14. Performance Tips

  • Use Redis for large apps
  • Monitor hit/miss ratio
  • Use cache tags for grouped data
  • Pre-warm cache after deployment
  • Avoid huge object serialization

Share: 

No comments yet! You be the first to comment.

Leave a Reply

Your email address will not be published. Required fields are marked *