thebigk's avatar
Level 13

Cache Records Before pagination

I've a thread model which 'hasMany' replies. Now, in order to render a thread with all the replies, I'm fetching thread and replies separately.

I'm trying to use the following logic to cache replies to any thread -

$replies =  Cache::store('redis')->tags(['thread_' . $thread->id . '_replies'])->rememberForever('thread_' . $thread->id . '_replies_' . $page, function () use($thread) {
            return $thread->replies()->with(['owner', 'likes'])->withCount('likes')->paginate(20);
        });

However, with this approach, I've to cache each page separately. This makes it difficult to flush cache when a reply is posted or an existing reply is liked. I was thinking if there was a way to store all the replies to a thread in cache, and paginate them after retrieving.

Is there any way to do that? Would really appreciate your help.

0 likes
2 replies
NickVahalik's avatar

Do you have any good information about what is actually slow? Is loading the entire thread slow? Or just adding the replies? My reason for asking is that you might be prematurely caching information which isn't very slow at all. It might make more sense to cache the individual replies and not worry about caching the pagination at all—but rather focus on caching the eagerly loaded objects.

thebigk's avatar
Level 13

@NickVahalik - It's not slow at all. I've a Redis server sitting almost idle and I thought I'd rather put it to some good use.

I'm actually use it to cache stuff that's read more often than updated - and it works really well. This is my first attempt at using cache for forum which is frequently updated.

Please or to participate in this conversation.