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

jericopulvera's avatar

Session question laravel

Why is my view count still increments even though I have session putted?

  • what is wrong with my code?
  • is this an error within laravel?
if(! ( Session::get($id) == $id)){
            Post::where('id', $id)->increment('view_count');
            dd('added count');
            Session::put('id', $id);
          }
  • The id is the blog->id
0 likes
6 replies
MartinDevNow's avatar

Your script will continue to increment because of:

dd('added count');

.. that kills the process and so:

Session::put('id', $id);

is never run.

Try commenting out the dd() line and see if that works.

1 like
jericopulvera's avatar

@MartinDevNow still does the same I even tried putting the Session::put in the top.

OleksandrZnaidiuk's avatar
Level 6

Here is the problem Session::get($id). When you put in the session Session::put('id', $id); this actually means that you store some value $id by key = 'id'. To get this data back you need to use the key 'id' ... Session::get('id');

Your code trying to get some value from the Session by blog->id that stored in $id variable that some integer. Get you data back by key that you store it - 'id' (string), not blog->id (integer).

1 like
OleksandrZnaidiuk's avatar

Code below must work how you expected.

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

More explaining:

$id = 777;               // Integer
Session::put('id', $id); // 'id' => 777
Session::get('id');      // you get your integer 777
Session::get($id);       // in this case you get null, 777 => ?
4 likes
jericopulvera's avatar

@AlexanderZnaydyuk this worked but if a user switch between two blogs while refreshing those two blogs keeps updating the count.

Please or to participate in this conversation.