Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

jericopulvera's avatar

Session, Popular post and View Count

I'm making a popular blogs display based on view count but I'm having problem using session.

My blog show method

  public function show(Request $request, $id)
    {
        if (Session::get('id') !== $id) {
            Post::where('id', $id)->increment('view_count');
            Session::put('id', $id);
        }

           $comments = Comment::where('blog_id', $id)->with('user')->orderBy('created_at', 'ASC')->paginate(4);
           $blogs = Post::where('id', $id)->with('user')->first();
       
  • a user only updates the count when he viewed it once
  • but when a user keeps changing between two blogs the two blogs keeps incrementing by 1.
  • can you please suggest the best and easiest way to solve this problem. thank you!
0 likes
5 replies
SaeedPrez's avatar
Level 50

There are many ways to do this,..

Basically you need to save the Id of all blogs the user views. So we need to a save an array or we could format the session keys like blog_1 where 1 is the Id.

$blogKey = 'blog_' . $id;

// Check if blog session key exists
// If not, update view_count and create session key
if (!Session::has($blogKey)) {
    Post::where('id', $id)->increment('view_count');
    Session::put($blogkey, 1);
}
5 likes
jericopulvera's avatar

@Prez amazing!!! I've been testing this for hours and you solved it easily.

SaeedPrez's avatar

@Eco012390 you'll get there, I've been doing this on and off for ~20 years.

1 like
Osama-Mustafa's avatar

I searched many articles on the internet, and found many complicated solutions, but your answer is great and works as expected ... Thank you very much

journey4tech's avatar

how can we increment more than 1 time . i want to show more view count in my blog. please help me

Please or to participate in this conversation.