Counting page views with Laravel

前端 未结 5 910
北荒
北荒 2021-02-01 10:02

I want to implement page view counter in my app. What I\'ve done so far is using this method :

public function showpost($titleslug) {
        $post = Post::where         


        
5条回答
  •  萌比男神i
    2021-02-01 10:29

    As quoted in @ milo526's comment, you can record all hits to your pages in a unique way instead of an increment. With this you have many possibilities to search for access information, including the listing of the posts sorted by most viewed.

    Create a table to save your view records:

    Schema::create("posts_views", function(Blueprint $table)
            {
                $table->engine = "InnoDB";
    
                $table->increments("id");
                $table->increments("id_post");
                $table->string("titleslug");
                $table->string("url");
                $table->string("session_id");
                $table->string("user_id");
                $table->string("ip");
                $table->string("agent");
                $table->timestamps();
            });
    

    Then, create the corresponding model:

    id_post = $post->id;
                $postsViews->titleslug = $post->titleslug;
                $postsViews->url = \Request::url();
                $postsViews->session_id = \Request::getSession()->getId();
                $postsViews->user_id = \Auth::user()->id;
                $postsViews->ip = \Request::getClientIp();
                $postsViews->agent = \Request::header('User-Agent');
                $postsViews->save();
        }
    
    }
    

    Finally, your method:

    public function showpost($titleslug)
    {
        $post = PostsViews::where('titleslug', '=' ,$titleslug)->firstOrFail();
    
        PostsViews::createViewLog($post);
    
        //Rest of method...
    }
    

    To search the most viewed posts in the last 24 hours:

    $posts = Posts::join("posts_views", "posts_views.id_post", "=", "posts.id")
                ->where("created_at", ">=", date("Y-m-d H:i:s", strtotime('-24 hours', time())))
                ->groupBy("posts.id")
                ->orderBy(DB::raw('COUNT(posts.id)', 'desc'))
                ->get(array(DB::raw('COUNT(posts.id) as total_views'), 'posts.*'));
    

    Note that in PostsViews, you have data that can help further filter your listing, such as the session id, in case you do not want to consider hits from the same session.

    You may need to adapt some aspects of this solution to your final code.

提交回复
热议问题