withCount not working with Cache::remember

Published 1 week ago by jorgeyoma

Hi.

I have a function in PostController that searches for the tags that have been used in Posts and gives this data to the view.

I want to cache this info but now it gives me all the tags, no matter if they are used or not.

This works and gives me only the tags with posts.

        $tags =  Tag::withCount(['posts' => function ($query) {
          $query->active();
        }])->having('posts_count','>',0)->get();

This gives me all the tags. What's wrong?

      
$tags = Cache::remember('tags', 3600, function () {

       return  Tag::withCount(['posts' => function ($query) {
          $query->active();
        }])->having('posts_count','>',0)->get();

     });
Best Answer (As Selected By jorgeyoma)
tykus

No reason that it should not work; are you sure you are not seeing an earlier cached result set; or are you using the tags key for another cached query result?

tykus
tykus
1 week ago (574,630 XP)

No reason that it should not work; are you sure you are not seeing an earlier cached result set; or are you using the tags key for another cached query result?

jorgeyoma

@tykus the key was duplicated.

Please sign in or create an account to participate in this conversation.