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)redisdatabasememcachedarray(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 namettl: 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.
Projects to explore next
Source-code projects from the KritiMyantra catalogue. Check each project's details before buying.
Flask Authentication System (Free Version) - Kritim Yantra
🛠 Features✔ Google & GitHub Authentication✔ User Registration & Login✔ Profile/Dashboard Access✔ Secure & Mi...
Flask Blog CMS with Admin Dashboard — Python Source Code
A Flask-based blogging website with a built-in admin dashboard. Manage articles, images, categories, tags and featured p...
Laravel 12 + ReactJS Starter Kit: Add Multi-Language Support (Arabic, English, Spanish) with Blog CRUD
🚀 Installation & Setup Download & Extract Get the ZIP from kritimyantra.com and extract it. Includes preconfigu...
Comments
No comments yet. Be the first to comment.
Sign in to join the discussion.