计算页面视图laravel 5.2

时间:2017-08-01 17:02:52

标签: php html laravel

如何计算网页浏览量。每次保存到数据库。请。我正在使用laravel 5.2。 我尝试了几个包但不能?

3 个答案:

答案 0 :(得分:3)

您可以创建一个存储所有视图记录的表,这样您就可以对视图进行计数,包括按会话,ip等过滤。

首先,创建表格:

Schema::create("browsing_history", function(Blueprint $table)
        {
            $table->engine = "InnoDB";

            $table->increments("id");
            $table->string("url");
            $table->string("session_id");
            $table->string("user_id");
            $table->string("ip");
            $table->string("agent");
            $table->timestamps();
        });

其次,创建相应的模型:

<?php namespace App\Models;

class BrowsingHistory extends \Eloquent {

    protected $table = 'browsing_history';

    public static function createLog() {
            $browsingHistory = new BrowsingHistory();
            $browsingHistory->url = \Request::url();
            $browsingHistory->session_id = \Request::getSession()->getId();
            $browsingHistory->user_id = \Auth::user()->id;
            $browsingHistory->ip = \Request::getClientIp();
            $browsingHistory->agent = \Request::header('User-Agent');
            $browsingHistory->save();
    }

}

第三,通过覆盖视图控制器的构建器来添加对日志的调用:

public function __construct()
{
    BrowsingHistory::createLog();
}

要查询计数,忽略同一会话的点击次数:

public function countViewsPerSession($url)
{
    return BrowsingHistory::where("url", $url)
        ->groupBy("session_id")
        ->count();
}

答案 1 :(得分:2)

实现此目的的最简单方法是为视图添加数据库列,并在每次为用户加载页面时将其递增。然后,您可以通过IP地址或发出请求的用户分隔唯一视图。

答案 2 :(得分:0)

多亏了@Jean_Macros,我才得以解决问题

我建议任何人都遵循@Jean_Macros代码以获取详细信息,但

要阻止页面每次重装增加,请执行以下操作

您要去的地方

将此代码放入您的模型

protected $table = 'page_view_counts';

public static function createLog($page_owner_id) {
    $browser = new BrowserDetection(); //just a function i wrote
    // special values
    $address = getRealIp(); //just a function i wrote
    $browser = $browser->getName()." ver-".$browser->getVersion();
    $url = Request::url();
    $session_id = Request::getSession()->getId();
    $log_exists = (new PageViewCount)->where([['page_id', '=', $page_owner_id], ['session_id', '=', $session_id], ['url', '=', $url]])->exists();
        if (!$log_exists) {
            $pageViewCount = new DiaryViewCount();
            $pageViewCount->url = $url;
            $pageViewCount->session_id = $session_id;
            $pageViewCount->diary_id = $page_owner_id;
            $pageViewCount->address = $address;
            $pageViewCount->browser = $browser;
            $pageViewCount->save();
        }
}