Avoid Unnecessary API Calls with Laravel's Cache::remember()
Imagine your application displays popular categories on every page.
You might query them repeatedly:
$categories = Category::orderByDesc('posts_count')
->take(10)
->get();
If hundreds of users request the page, the same query can run again and again.
If the data doesn't change frequently, that's unnecessary work.
Use Cache::remember()
Laravel provides a simple way to cache the result:
use Illuminate\Support\Facades\Cache;
$categories = Cache::remember(
'popular-categories',
3600,
fn () => Category::orderByDesc('posts_count')
->take(10)
->get()
);
The first request runs the query and stores the result.
Later requests use the cached value.
How It Works
The flow is simple:
First request
↓
Cache doesn't exist
↓
Run query
↓
Store result
↓
Return result
Next request
↓
Cache exists
↓
Return cached result
Choose the Right Expiration
The second argument defines how long the value should remain cached.
For example:
Cache::remember('popular-categories', 3600, ...);
Here, 3600 represents one hour.
For data that changes frequently, use a shorter duration.
For relatively stable data, a longer duration may make sense.
Clear the Cache When Data Changes
If you update the categories, you may want to remove the old cached value:
Cache::forget('popular-categories');
The next request will execute the query again and store the fresh result.