Laravel Livewire pagination with cache

Monday Nov 21st 2022
2 min read

This blog / site is made with Laravel and I use Livewire and Alpine.js with it. When I was coding my article listings I noticed that my pagination has stopped working after I cached some results.

I have used Livewires WithPagination trait and it worked fine and then I added the Cache.

Here is my Article listing before I fixed the bug:

1$articles = Cache::remember('home_articles', config('blog.cache_time'), function(){
2 return Article::published()->paginate(5);

At first glance there is no issue here. Article listing works fine until you try to change pages. Then it loads the same results from cache. So the solution is to add page number to the cache name.

A bit head scratching and I found $this->page variable. Here is the fixed listing:

1$articles = Cache::remember('home_articles_'.$this->page, config('blog.cache_time'), function(){
2 return Article::published()->paginate(5);

So now when page is changed it loads the current pages cached results. And the pagination works just fine since it does not always load the first pages results.

I still need to add Cache tags so I can flush specific types of caches.


We use Mastodon to show our comments. You only need to post a reply for the corresponding toot. We cache our comments here so it may take a couple of minutes to show up here.
Join the conversation