Home > Enterprise >  Count views with Session
Count views with Session

Time:10-14

I'm new to laravel. I found a way here how to count article views, I used it on my own and it works as it should

$viewed = Session::get('viewed_article', []);
        if (!in_array($article->id, $viewed)) {
            $article->increment('views');
            Session::push('viewed_article', $article->id);
        }

But the only thing I do not fully understand is how it works and what it does, which makes me feel a little uneasy.

Who is not difficult, can you explain how this function works?

CodePudding user response:

The first line:

$viewed = Session::get('viewed_article', []);

uses the Session facade to get the data with the key viewed_article from the session, or if nothing exists for that key, set $viewed to an empty array instead (the second argument sets the default value).

The next line, the if statement:

if (!in_array($article->id, $viewed)) {

makes sure that the current article id is not in the $viewed array.

If this condition is true (i.e. the article is not in the array), then the views are incremented (i.e. increased by one) on the article:

$article->increment('views');

Lastly, the article id is added into the viewed_article session data, so the next time the code runs, it won't count the view again:

Session::push('viewed_article', $article->id);
  • Related