Sitemap

Laravel Pre-Caching: Boost Your Application Speed And Performance!

3 min readApr 5, 2023

--

Laravel Pre-Caching

One of the most important things to have a more performant and blazing fast website is using pre-cache method.

Laravel already made caching so much easy to use. Imagine we have a LessonController which is like below:

A simple way to use cache in Laravel is like this:

There are many things about caching in Laravel like: drivers, configs and etc… . But now we just want to focus on this article subject which is “Pre-Caching with Laravel”!

With these implementations when a user hit the specified route Laravel will cache result for a certain amount of time, but we want to be even more faster, so first of all we will create an ArticleService to move cache logic and have a more cleaner controller. ArticleController and ArticleService will look like these:

  • ArticleController:
Laravel Cache
  • ArticleService:

Second of all, we will create a Laravel command CacheArticles like below:

php artisan make:command CacheArticles

  • CacheArticles Command:

On this command we just need to call the _index() method on ArticleService and don’t forget to add the command to App\Console\Kernel.php:

After that without need to hit the route we have a pre-cache resource that is pre-cached!

Don’t forget to pass $perPage parameter to paginate() method because it is very important with this approach, and another gotcha that we can fall into is caching only the first page of articles so if we want to prevent that, we should put $perPage parameter to the cache key!

READ MORE:

--

--

Responses (5)