Laravel ‐ Chapter 15 - pierre-akhrass/Lavarel-Docs GitHub Wiki

Caching is critical for optimizing the performance of web applications. Laravel provides an elegant and flexible caching system that supports various drivers and advanced strategies to store and retrieve data.


Why Use Cache?

When the same resource (e.g., an API endpoint) is requested repeatedly, processing it again is wasteful—especially for expensive operations like querying large datasets or rendering HTML.

For example:

public function all(): JsonResponse {
    return response()->json(Post::get());
}

Returning 10,000+ records every time is inefficient. Laravel's cache system helps mitigate this by storing the result temporarily.


Laravel Cache Backends

Laravel supports several caching drivers:

  • file (default)
  • database
  • redis
  • memcached
  • array (for testing)

Define the cache driver in .env:

CACHE_STORE=file

Common Cache Methods

Here are the most commonly used cache methods:

Method Description
get() Retrieve a cached item
has() Check if a key exists in cache
put() Store an item with a duration
putMany() Store multiple items at once
add() Store if key doesn't exist
pull() Get and delete
many() Retrieve multiple keys
remember() Return cached or store result if missing
rememberForever() Store permanently if not cached
increment() Increment numeric value
decrement() Decrement numeric value
forever() Store an item permanently
forget() Delete a specific cache key
flush() Clear all cache

Method Examples

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

Cache::put('key', 'value', now()->addMinutes(10));
Cache::putMany(['k1' => 'v1', 'k2' => 'v2'], now()->addMinutes(5));

Cache::add('key', 'value', now()->addMinutes(10));

Cache::pull('key');

Cache::has('key');
Cache::forget('key');
Cache::flush();

Cache::increment('counter');
Cache::decrement('counter');

Caching Database Responses

Use remember():

Cache::remember('posts', now()->addMinutes(10), function () {
    return Post::all();
});

Equivalent code:

if (Cache::has('posts')) {

    return Cache::get('posts');

} 
else 
{
    $posts = Post::all();

    Cache::put('posts', $posts, now()->addMinutes(10));

    return $posts;

}

Or rememberForever():

Cache::rememberForever('posts', function () {
    return Post::all();
});

Caching in a Controller

public function all(): JsonResponse {
    return Cache::remember('posts_index', now()->addMinutes(10), function () {
        return Post::all();
    });
}

Avoid storing complex JSON responses directly in the cache callback:

// Bad: Can exhaust memory
return Cache::remember('posts_index', now()->addMinutes(10), function () {
    return response()->json(Post::all());
});

Instead:

$posts = Cache::remember('posts_index', now()->addMinutes(10), fn() => Post::all());
return response()->json($posts);

Caching HTML View Content

You can also cache rendered HTML strings:

public function show(Post $post): String {
    return Cache::rememberForever('post_show_'.$post->id, function () use ($post) {
        return view('blog.show', compact('post'))->render();
    });
}

Clear Cache on Update:

Cache::forget('post_show_'.$post->id);

Avoid Database Calls if Cache Exists

Change route to receive post ID manually:

public function show(int $id): String {
    if (Cache::has('post_show_' . $id)) {
        return Cache::get('post_show_' . $id);
    }

    $post = Post::find($id);
    $view = view('blog.show', compact('post'))->render();
    Cache::put('post_show_' . $id, $view);
    return $view;
}

Available Cache Stores

Store Description
file Default. No config needed. Stores in storage/framework/cache/data
database Requires php artisan cache:table + migration
memcached Fast, memory-based. Requires server & PHP extension
redis In-memory DB. Extremely fast. Requires Redis server
array Non-persistent. For testing only

Example in .env:

CACHE_STORE=redis

Switching to Redis

.env

CACHE_STORE=redis
REDIS_HOST=127.0.0.1
REDIS_PORT=6379

config/database.php (redis section):

'redis' => [
    'client' => env('REDIS_CLIENT', 'phpredis'),
    '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),
    ],
];

Route Caching

Speed up production apps by caching route definitions:

php artisan route:cache

Reads all your routes (from routes/web.php, routes/api.php, etc.)

Compiles them into a cached file stored in: bootstrap/cache/routes-v7.php (or similar)

Improves performance by reducing file parsing and route registration time

php artisan route:clear

Use this if:

You changed a route.

You added a closure route.

You're switching between environments.


Testing Cache Performance

Use Postman or Axios to test performance.

Example:

axios.get('/api/post').then(res => console.log(res.data));

You'll notice faster load times when using cached data vs. querying DB repeatedly.