Laravel 13 Cache Tutorial: Cache::remember(), Cache::flexible() & Performance Optimization

Laravel 13 Cache Tutorial: Cache::remember(), Flexible Cache & Performance Optimization

If your Laravel application is making the same database queries again and again, your application can become slower as the amount of data and number of users increases. Laravel provides a powerful caching system that allows developers to temporarily store frequently used data and retrieve it much faster.

In this Laravel 13 Cache Tutorial, we will learn how Laravel caching works, how to use Cache::put(), Cache::get(), Cache::remember(), Cache::rememberForever(), Cache::forget() and the modern Cache::flexible() method.

We will also look at Redis caching and practical techniques that can help improve the performance of a Laravel application.


What Is Cache in Laravel?

Cache is temporary storage used to keep frequently accessed data so that the application does not have to perform the same expensive operation every time.

For example, suppose your application needs to fetch 10,000 products from the database. If the same product list is requested repeatedly, executing the same database query for every request can create unnecessary database load.

Instead, we can store the result in the cache and retrieve it from the cache for subsequent requests.


Database Query
      ↓
Cache Data
      ↓
Fast Response

Laravel provides a unified cache API that can work with different cache backends.

Why Should You Use Laravel Cache?

  • Reduce repeated database queries
  • Improve application response time
  • Reduce database load
  • Improve scalability
  • Improve API performance
  • Reduce expensive calculations
  • Store frequently accessed application data

Laravel Cache Configuration

Laravel provides cache configuration through the application's cache configuration. Depending on the Laravel application and environment, you can use different cache stores.

Common cache backends include:

  • Database
  • Redis
  • Memcached
  • File
  • DynamoDB

For development, a simple cache driver can be sufficient. For high-traffic production applications, Redis is commonly used for fast cache operations.


How to Store Data Using Cache::put()

The Cache::put() method can be used to store a value in the cache for a specific amount of time.


use Illuminate\Support\Facades\Cache;

Cache::put('site_name', 'Developer Sahayak', 600);

In this example, the value is stored using the key site_name. The third parameter represents the cache lifetime in seconds.

Here, 600 means approximately 10 minutes.

Example


use Illuminate\Support\Facades\Cache;

Cache::put(
    'website_name',
    'Developer Sahayak',
    600
);

How to Get Cached Data Using Cache::get()

After storing data, you can retrieve it using the Cache::get() method.


use Illuminate\Support\Facades\Cache;

$value = Cache::get('website_name');

If the cache key does not exist, Laravel returns null by default.

Using a Default Value


$value = Cache::get(
    'website_name',
    'Default Website'
);

If the cache item does not exist, Laravel will return Default Website.


Laravel Cache::remember() Method

One of the most useful Laravel caching methods is Cache::remember(). It is especially useful when you want to cache the result of a database query.

The basic idea is simple:

  1. Laravel checks whether the cache exists.
  2. If the cache exists, Laravel returns the cached value.
  3. If the cache does not exist, Laravel executes the callback.
  4. The result is stored in the cache.
  5. The cached result is returned.

Example


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

$products = Cache::remember(
    'products',
    600,
    function () {
        return Product::all();
    }
);

This example avoids executing the database query every time the application requests the product list.


Laravel Cache::remember() With Query Builder

You can also use Cache::remember() with Laravel's query builder.


use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;

$users = Cache::remember(
    'active_users',
    300,
    function () {
        return DB::table('users')
            ->where('status', 'active')
            ->get();
    }
);

This approach is useful for frequently requested database results that do not change every second.


Cache::rememberForever()

Laravel also provides Cache::rememberForever(). It retrieves an existing cached value or executes the callback and stores the result without a normal expiration time.


use Illuminate\Support\Facades\Cache;

$settings = Cache::rememberForever(
    'website_settings',
    function () {
        return \App\Models\Setting::all();
    }
);

Use this method carefully for data that should remain cached until you explicitly remove or refresh it.


How to Delete Cache Using Cache::forget()

When cached data becomes outdated, you may need to remove it. Laravel provides the Cache::forget() method.


use Illuminate\Support\Facades\Cache;

Cache::forget('website_settings');

After deleting the cache, the next request can rebuild the cached value.


Clearing Laravel Cache

During development or troubleshooting, you may need to clear Laravel's application cache.


php artisan cache:clear

You can also use Laravel's optimization commands when preparing an application for production.


php artisan optimize

Laravel's production deployment documentation recommends caching configuration, events, routes and views as appropriate for production deployments.


Laravel 13 Cache::flexible()

Laravel 13 provides the Cache::flexible() method for a stale-while-revalidate style caching approach.

This can be useful when you want users to receive cached data quickly while allowing Laravel to refresh stale data in the background.

Example


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

$products = Cache::flexible(
    'products',
    [300, 600],
    function () {
        return Product::query()->get();
    }
);

The two values define the fresh and stale periods. The exact behavior should be selected based on how frequently your application's data changes and how fresh that data needs to be.

This approach can be particularly useful for data that is expensive to generate but does not need to be recalculated for every request.


Laravel Cache::touch()

Laravel 13 also provides Cache::touch(), which can be used to extend the TTL of an existing cache item without retrieving and storing the value again.


use Illuminate\Support\Facades\Cache;

Cache::touch('products', 600);

This can be useful when you want to extend the lifetime of an existing cached value.


Laravel Cache With Redis

Redis is a popular choice for Laravel applications that require fast cache operations. Laravel supports Redis as a cache backend.

After configuring Redis for your application, you can use Laravel's normal cache API without changing the business logic of your application.

Example


use Illuminate\Support\Facades\Cache;

Cache::store('redis')->put(
    'popular_products',
    $products,
    600
);

You can also retrieve data from the Redis cache store:


$products = Cache::store('redis')->get(
    'popular_products'
);

This makes it possible to use a dedicated Redis store for frequently accessed data.


Practical Laravel Cache Example

Let's create a practical example where we want to cache a list of active products.

Controller


<?php

namespace App\Http\Controllers;

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

class ProductController extends Controller
{
    public function index()
    {
        $products = Cache::remember(
            'active_products',
            600,
            function () {
                return Product::where(
                    'status',
                    'active'
                )->get();
            }
        );

        return view(
            'products.index',
            compact('products')
        );
    }
}

Now the application does not need to execute the same database query on every request while the cached value is available.


Cache Data After Creating a Product

When application data changes, the related cache may need to be invalidated.

For example, after creating a product:


Cache::forget('active_products');

The next request can execute the database query again and rebuild the cache.


Cache Naming Best Practices

Good cache keys make applications easier to maintain.

Instead of using unclear keys such as:


data
list
cache1
test

use descriptive keys:


products.active
products.featured
users.active
orders.recent
settings.website

For user-specific data, include the user ID in the key.


$userId = auth()->id();

$key = "user.{$userId}.profile";

When Should You Use Laravel Cache?

Caching is useful when the same data is requested frequently and does not need to be calculated again for every request.

Good Candidates for Caching

  • Popular products
  • Categories
  • Website settings
  • Dashboard statistics
  • API responses
  • Frequently used configuration data
  • Expensive database queries
  • External API responses

Data You Should Treat Carefully

  • Highly dynamic financial information
  • Real-time inventory
  • Security-sensitive information
  • Data that changes on almost every request

The correct caching strategy depends on how fresh the data must be and how expensive it is to regenerate.


Laravel Cache vs Database Query

Database Query Cache
Reads data from the database Reads previously stored data
Can be expensive for repeated queries Usually reduces repeated work
Always gets current database data May contain data that is temporarily stale
Useful for frequently changing data Useful for frequently requested data

Common Laravel Cache Mistakes

1. Caching Everything

Not every database query needs caching. Adding cache everywhere can make application logic harder to understand and may introduce stale-data problems.

2. Using Very Long TTL Values

If data changes frequently, a very long cache lifetime can cause users to see outdated information.

3. Forgetting Cache Invalidation

When important data changes, related cached values may need to be removed or refreshed.

4. Poor Cache Key Design

Cache keys should clearly identify the data being stored.

5. Caching Sensitive Data Without Planning

Before caching private or security-sensitive information, understand where the cache data is stored and who can access it.


Laravel Cache Performance Optimization Tips

  • Cache expensive queries that are requested frequently.
  • Use meaningful cache keys.
  • Choose TTL values based on data freshness requirements.
  • Invalidate cache when important data changes.
  • Use Redis when your infrastructure benefits from a fast centralized cache.
  • Monitor cache hit and miss behavior where appropriate.
  • Avoid caching data that changes constantly.
  • Test cache behavior before deploying to production.

Frequently Asked Questions

What is Laravel Cache?

Laravel Cache is a unified caching system that allows applications to store frequently used data temporarily and retrieve it without repeating expensive operations.

What is Cache::remember() in Laravel?

Cache::remember() retrieves an existing cache value or executes a callback, stores its result for the specified duration and returns the result.

What is Cache::flexible()?

Cache::flexible() supports a stale-while-revalidate style caching pattern, allowing stale data to be served while the application refreshes the cached value.

Is Redis required for Laravel Cache?

No. Laravel supports multiple cache stores. Redis is one option and can be useful for applications that require fast centralized caching.

How do I clear Laravel cache?

You can clear the application cache using:


php artisan cache:clear

Does caching make Laravel faster?

Caching can improve performance when it avoids repeated expensive operations such as database queries or external API requests. The actual improvement depends on the application, cache backend, workload and cache hit rate.


Conclusion

Laravel's caching system provides developers with a simple way to reduce repeated work and improve application performance.

For basic caching, methods such as Cache::put(), Cache::get() and Cache::forget() are useful. For database queries and expensive operations, Cache::remember() is especially convenient.

Laravel 13 also provides modern caching capabilities such as Cache::flexible() and Cache::touch(), giving developers more options for handling cached data and expiration.

The key is not to cache everything. Instead, identify expensive operations that are frequently repeated and design a caching strategy around the application's data freshness requirements.


Related Laravel Tutorials

  • Laravel 13 API Authentication with Sanctum
  • Laravel 13 Queue and Background Jobs
  • Laravel 13 Redis Configuration
  • Laravel 13 Database Optimization
  • Laravel 13 Eloquent Performance Optimization

0 Comments