Laravel 5.3 文章访问计数器问题:刷新页面重复递增view_count
Got it, let's fix that duplicate view count issue you're facing. The problem right now is that every HTTP request (including refreshes) triggers the increment, which isn't what we want—we only want to count a unique view per user session (or for a set period of time). Here's how to adjust your code:
Fixing Duplicate View Count Increments on Page Refresh
Solution 1: Use Session to Track Viewed Posts
Modify your PostController's show method to check if the user has already viewed this post in their current session before incrementing the count:
public function show(Post $post) { // Check if the post ID isn't marked as viewed in the session if (!session()->has('viewed_posts') || !in_array($post->id, session('viewed_posts'))) { $post->increment('view_count'); // Add the post ID to the session to mark it as viewed session()->push('viewed_posts', $post->id); } return view("site.show", compact('post')); }
How this works:
- We use Laravel's built-in session system to track which posts the current user has viewed during their browsing session.
- When a user lands on a post, we first check if the post's ID exists in the
viewed_postssession array. - If it doesn't, we increment the view count and add the ID to the session.
- This ensures even repeated refreshes from the same user won't bump the count multiple times in one session.
Solution 2: Use Cookies for Longer-Term Tracking (Optional)
If you want to stop duplicate counts across browser sessions (e.g., prevent the same user from incrementing the count for 24 hours), use cookies instead:
public function show(Post $post) { $cookieName = "viewed_post_{$post->id}"; // Check if the user hasn't viewed this post in the last 24 hours if (!request()->cookie($cookieName)) { $post->increment('view_count'); // Set a cookie that expires after 24 hours (86400 seconds) return view("site.show", compact('post'))->cookie( $cookieName, '1', 86400 ); } return view("site.show", compact('post')); }
How this works:
- We create a unique cookie name for each post using its ID, so we can track views per post individually.
- If the cookie doesn't exist, we increment the count and set a cookie that lasts 24 hours (adjust the expiration time to fit your needs).
- This stops the same user from triggering multiple increments until the cookie expires.
Quick Notes:
- Session-based tracking resets when the user closes their browser, while cookie-based tracking persists for your chosen timeframe.
- For authenticated users only, you could add a
post_viewstable to log user IDs and post IDs for even more accurate unique tracking—but that's a more complex setup.
内容的提问来源于stack exchange,提问作者Ogi
相关产品推荐
相关产品推荐

