Skip to main content

Black Friday 2025! Only until December 1st: coupon FRIDAY25 for 40% off Yearly/Lifetime membership!

Read more here

In this lesson, let's talk about caching. For example, categories will mostly stay the same or could not change for years or even ever. For such cases, we can introduce cache and not make any queries to the database.


Let's introduce a cache for 24 hours.

app/Http/Controllers/Api/CategoryController.php:

use Illuminate\Support\Facades\Cache;
 
class CategoryController extends Controller
{
public function index()
{
abort_if(! auth()->user()->tokenCan('categories-list'), 403);
 
return CategoryResource::collection(Cache::remember('categories', 60*60*24, function () {
return Category::all();
}));
}
 
// ...
}

For checking queries, I will be using the Laravel Telescope package.

We can see the query was executed after going to the /categories endpoint in the Telescope.

The query won't be executed for the next 24 hours.

But we can do even better in this case. We can cache forever and clear the cache automatically, instead of doing it manually when a new category is created.

First, the caching. Instead of remember, we use...

The Full Lesson is Only for Premium Members

Want to access all of our courses? (31 h 16 min)

You also get:

55 courses
Premium tutorials
Access to repositories
Private Discord
Get Premium for $129/year or $29/month

Already a member? Login here

Comments & Discussion

V
Velkacem ✓ Link copied!

The caching systel is good!

O
Ohansyah ✓ Link copied!

IMHO, storing json is lighter than Illuminate\Database\Eloquent\Collection you can compare it by yourself

dump(Category::all(), Category::all()->toJson());

but it need tiny extra works to decode it

return CategoryResource::collection(json_decode(Cache::remember('categories', 10, function () { return Category::all()->toJson(); })));