Skip to content

Commit 0511795

Browse files
committed
Smart page view caching
1 parent 22136fe commit 0511795

File tree

1 file changed

+23
-5
lines changed

1 file changed

+23
-5
lines changed

app/Models/Post.php

Lines changed: 23 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -151,10 +151,28 @@ public function getViewCount(): int
151151
throw new \BadMethodCallException('Analytics are not enabled');
152152
}
153153

154-
return cache()->remember(
155-
"post.{$this->id}.views",
156-
now()->addMinutes(config('analytics.view_count_cache_duration')),
157-
fn() => PageView::where('page', route('posts.show', $this, false))->count()
158-
);
154+
$cacheKey = "post.{$this->id}.views";
155+
$cacheDuration = config('analytics.view_count_cache_duration');
156+
157+
// Get the cached value (even if expired)
158+
$value = cache()->get($cacheKey);
159+
160+
if ($value !== null) {
161+
// If the cache exists but is stale, dispatch background refresh
162+
if (! cache()->has($cacheKey)) {
163+
dispatch(function () use ($cacheKey, $cacheDuration) {
164+
$newValue = PageView::where('page', route('posts.show', $this, false))->count();
165+
cache()->put($cacheKey, $newValue, now()->addMinutes($cacheDuration));
166+
})->afterResponse();
167+
}
168+
169+
return $value;
170+
}
171+
172+
// If no cached value exists at all, fetch and cache synchronously
173+
$value = PageView::where('page', route('posts.show', $this, false))->count();
174+
cache()->put($cacheKey, $value, now()->addMinutes($cacheDuration));
175+
176+
return $value;
159177
}
160178
}

0 commit comments

Comments
 (0)