Laravel 12 API Caching Strategies: Faster Responses, Less Load

Author

Kritim Yantra

Jun 25, 2025

Laravel 12 API Caching Strategies: Faster Responses, Less Load

“Why make 100 database calls when one can be enough?”

When your API starts growing, every request adds load on your database, slows down the response, and drains your server resources. The solution? Caching.

In this blog, you’ll learn how to boost the speed of your Laravel 12 API using caching strategies — step by step.


🚀 What Is Caching?

Caching is like storing your homework in your backpack instead of rewriting it every time a teacher asks.

Instead of querying the database every time someone hits your API, you store the result temporarily — so it loads in milliseconds.


🧠 Why Use API Caching?

  • Faster API responses
  • 🧠 Reduced database queries
  • 💰 Lower server load and hosting costs
  • 📈 Better scalability under high traffic

🔧 Step 1: Configure Laravel Cache

Laravel supports various cache drivers:

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

In your .env file, set the driver:

CACHE_DRIVER=file

To boost performance in production, use Redis:

CACHE_DRIVER=redis

Install Redis via:

composer require predis/predis

🧪 Step 2: Cache API Data in Controller

Let’s say you have a PostController@index method:

Without cache:

public function index()
{
    return Post::latest()->paginate(10);
}

With cache:

use Illuminate\Support\Facades\Cache;

public function index()
{
    $posts = Cache::remember('posts_page_1', 60, function () {
        return Post::latest()->paginate(10);
    });

    return $posts;
}

✅ This caches the first page of posts for 60 minutes.


💡 remember() Breakdown

Cache::remember('key', ttl, function () {
    // Fetch from DB if not cached
});
  • key: Unique cache name
  • ttl: Time to live (in seconds/minutes)
  • Callback: What to run if cache is empty

🧹 Step 3: Clear Cache When Data Changes

Whenever a new post is created or updated, we should clear the cache.

In your store() or update() method:

Cache::forget('posts_page_1');

That way, new data is re-cached on the next request.


🔁 Step 4: Dynamic Caching (For Pagination)

If you paginate results (page 1, 2, 3...), cache each page separately:

$page = request()->get('page', 1);

$posts = Cache::remember("posts_page_$page", 60, function () {
    return Post::latest()->paginate(10);
});

This ensures page 1, 2, and so on are all individually cached.


📦 Bonus: Cache API with Tags (Advanced)

When using Redis or Memcached, you can tag cache items:

Cache::tags(['posts'])->remember('recent_posts', 60, function () {
    return Post::latest()->take(5)->get();
});

Then you can clear the tag when needed:

Cache::tags(['posts'])->flush();

This is powerful for large apps managing multiple cache segments.


🔐 Bonus Tip: Don’t Cache Sensitive or Auth-Based Data

Avoid caching personal or user-specific API responses unless you're keying them by user ID:

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

$dashboard = Cache::remember("dashboard_user_$userId", 300, function () {
    return [
        'stats' => fetchUserStats($userId),
        'notifications' => fetchAlerts($userId),
    ];
});

📊 Example: Cached API Response

{
  "cached": true,
  "data": [
    {
      "id": 1,
      "title": "Laravel Caching is Powerful"
    }
  ]
}

You can even include "cached": true in your response for debugging purposes.


🔄 Cache Expiration Best Practices

Data Type Expire After
Homepage posts 1 hour
User dashboard 5-15 minutes
Product catalog 1 day
Live stats 30 seconds

Use ttl based on how often the data changes.


🧠 Summary: Laravel API Caching Strategies

  • ️ Use Cache::remember() to store responses
  • 🔁 Use dynamic keys for pagination
  • ❌ Use Cache::forget() after create/update
  • 🚀 Use Redis for better performance
  • 🔖 Tag cache for grouped invalidation
  • 🛡️ Be careful with user-specific cache

📌 Pro Tip: Cache API Responses at Middleware Level

For heavy APIs, consider using middleware like:

composer require spatie/laravel-responsecache

This package caches entire API responses, not just data.

Ajay Yadav

Ajay Yadav

Senior Full-Stack Engineer

7 + Years Experience

Transforming Ideas Into Digital Solutions

I architect and build high-performance web applications with modern tech:

Laravel PHP 8+ Vue.js React.js Flask Python MySQL

Response time: under 24 hours • 100% confidential

Tags

Comments

No comments yet. Be the first to comment!

Please log in to post a comment:

Sign in with Google

Related Posts

Laravel 12 Roles and Permissions Setup: Complete Guide
Kritim Yantra Kritim Yantra
Feb 28, 2025
What Are Laravel 12 Service Providers?
Web Development
What Are Laravel 12 Service Providers?
Laravel Vue
Kritim Yantra Kritim Yantra
Mar 02, 2025
Understanding Laravel 12 Middleware
Web Development
Understanding Laravel 12 Middleware
Laravel Php
Kritim Yantra Kritim Yantra
Mar 05, 2025