Speed Up your APIs with Laravel Cache

Andrea Pollastri
2 min readJun 7, 2023

--

Laravel provides an expressive, unified API for various cache backends, allowing you to take advantage of their blazing-fast data retrieval and speed up your web application.

Using Laravel Cache is very simple and useful and it easily can be configured on File System, Redis, Memcached, or other drivers.

Why use it? There are several reasons to do it and there are many cases, for example… Suppose we have a website and a set of APIs to supply Posts, News, News Categories, Site Menus, etc to this website. These APIs need to recall our database every time we call them. In this case, a Cache system is a solution to avoid repetitive queries and to gain several microseconds in API responses.

In this example, we store in the cache a “News Show” query with a TTL of 3600 seconds and we assign to it a unique cache key and a set of Tags, useful to run selective Cache purges.

$currentNews = Cache::remember(sha1(request()->fullUrl()), 3600, function () {
return News::find(request()->id);
})->tags(['News', 'Api']);

return response->json($currentNews);

Using this snippet, we will obtain a sensible optimization of response speed after the first query every 3600 seconds.

Be careful! You have to evaluate what API can be cached and what no.
Not every type of response can be cached (for example user information, auth tokens, real-time information, etc can’t be cached for security and software architecture reasons).

For any other information, visit: https://laravel.com/docs/10.x/cache.
Did you ever try Laravel Cache?

--

--