Laravel 5 中的页面查看计数器

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28656448/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 10:59:44  来源:igfitidea点击:

Page View Counter in Laravel 5

laravel

提问by djangokillen

I'm wondering how you make a page view counter in Laravel 5. Is there any specific package that will help me out with this? I'm basically stuck, as the stable version of Laravel 5 was recently released.

我想知道你是如何在 Laravel 5 中制作页面浏览计数器的。有没有什么特定的包可以帮助我解决这个问题?我基本上被卡住了,因为 Laravel 5 的稳定版本最近发布了。

回答by Cyril de Wit

There are many ways to accomplish this, but each way has its pros and cons. In this answer, I'm going to show you some different ways to build a pageview counter.

有很多方法可以实现这一点,但每种方法都有其优点和缺点。在这个答案中,我将向您展示一些不同的方法来构建浏览量计数器。

#1 Simple column in a database table

#1 数据库表中的简单列

Let's say we are building a blog with posts and we want to keep track of the total pageviews count. What we can do is adding the column viewsor page_viewsto our posts database table. This column will store the total number of page views. We can increment this number every time a post is being shown to someone.

假设我们正在构建一个包含帖子的博客,并且我们想要跟踪总浏览量计数。我们可以做的是将列views或添加page_views到我们的帖子数据库表中。此列将存储页面浏览的总数。每次向某人显示帖子时,我们都可以增加此数字。

Example code:

示例代码:

public function show($id)
{
    $post = \App\Models\Post::find($id); // fetch post from database
    $post->increment('views'); // add a new page view to our `views` column by incrementing it

    return view('posts.show', [
        'post' => $post,
    ]);
}

Then inside your view (blade or php), you can get the column like this;

然后在您的视图(刀片或 php)中,您可以获得这样的列;

<div class="panel-footer">
    Views: {{ $post->views }}
</div>

But in this way, we will never know when people exactly viewed the post. It will only possible to get the total count and not the total views of the past 24 hours, 7 days, 14 weeks or from "12-01-2017".

但是通过这种方式,我们永远不会知道人们何时确切地查看了帖子。只能获取过去 24 小时、7 天、14 周或“12-01-2017”的总观看次数,而不是总观看次数。

#2 Extra table to store all views

#2 用于存储所有视图的额外表

This way is very different from way #1 because each page view will be stored as a record in the table.

这种方式与方式#1 非常不同,因为每个页面视图都将作为记录存储在表中。

Before writing the steps I want to tell you that I created a package called: Eloquent Viewable. It works exactly like #2.

在编写步骤之前,我想告诉您,我创建了一个名为:Eloquent Viewable. 它的工作原理与#2 完全一样。

First you need to create a database migration for the viewstable. This migration should contain the following:

首先,您需要为views表创建数据库迁移。此迁移应包含以下内容:

$table->increments('id')->unsigned();
$table->morphs('viewable');
$table->timestamps();

Then we need to create an Eloquent model, so we can fetch the views:

然后我们需要创建一个 Eloquent 模型,以便我们可以获取视图:

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class View extends Model
{
    protected $table = 'views';
    protected $guarded = ['id'];
}

Then add to each model that can be viewed or needs this functionality the following code. In this example, we are providing this functionality to the Postmodel.

然后将以下代码添加到可以查看或需要此功能的每个模型中。在这个例子中,我们为Post模型提供了这个功能。

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Carbon\Carbon;

class Post extends Model
{
    /**
     * Get the page views associated with the given model.
     *
     * @return \Illuminate\Database\Eloquent\Relations\MorphMany
     */
    public function views()
    {
        return $this->morphMany(
            \App\Models\View::class,
            'viewable'
        );
    }

    /**
     * Get the total number of views.
     *
     * @return int
     */
    public function getViewsCount()
    {
        return $this->views()->count();
    }

    public function getViewsCountSince($sinceDateTime)
    {
        return $this->views()->where('created_at', '>', $sinceDateTime)->count();
    }

    public function getViewsCountUpto($uptoDateTime)
    {
        return $this->views()->where('created_at', <', $uptoDateTime)->count();
    }
}

Now you can use the following methods to fetch the views counts.

现在您可以使用以下方法来获取观看次数。

// total number of views
$post->getViews();

// total number of views since the past 24 hours
$post->getViewsCountSince(Carbon::now()->subDay(1));

// total number of views upto 2 months ago
$post->getViewsCountUpto(Carbon::now()->subMonths(2));

回答by Ahmed Sayed Sk

This package is awesome and easy to use, i was get the same issue but i found with this package the solving Kryptonit3/Counter

这个包很棒而且易于使用,我遇到了同样的问题,但我发现这个包解决了 Kryptonit3/Counter

回答by AndHeiberg

If you would like to build this your self it would be quite easy.

如果您想自己构建它,那将非常容易。

Create a new middleware in app/Htpp/Middleware/PageViews.php:

在 中创建一个新的中间件app/Htpp/Middleware/PageViews.php

<?php

namespace App\Http\Middleware;

use Closure;

class PageViews
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @param  string|null  $guard
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        PageView::increment();

        return $next($request);
    }

}

Now add \App\Http\Middleware\PageViews::classto the $middleware property of your app/Http/Kernel.php class.

现在添加\App\Http\Middleware\PageViews::class到您的 app/Http/Kernel.php 类的 $middleware 属性。

Obviously I put in PageView::increment() which won't work cause PageView is not implemented. The simplest way to implement for you would probably to create a table with an int for pageviews and create a PageView model.

显然我放入了 PageView::increment() 这将不起作用,因为 PageView 没有实现。为您实现的最简单方法可能是创建一个带有 int 的表用于页面浏览并创建一个 PageView 模型。

A more advanced solution would be to store this in a cache and with a cron job save it to permanent storage once every hour. Just to limit the performance hit of saving page views.

更高级的解决方案是将其存储在缓存中,并使用 cron 作业每小时将其保存到永久存储中。只是为了限制保存页面浏览量的性能影响。

回答by ManuEl Magak

you can use this package, it's very easy to use

你可以使用这个包,它很容易使用

https://github.com/cyrildewit/eloquent-viewable#recording-views

https://github.com/cyrildewit/eloquent-viewable#recording-views

few things you can do once installed and configred:

安装和配置后您可以做的几件事:

// Return total views count
views($post)->count();

// Return total views count that have been made since 20 February 2017
views($post)->period(Period::since('2017-02-20'))->count();

// Return total views count that have been made between 2014 and 216
views($post)->period(Period::create('2014', '2016'))->count();

// Return total unique views count (based on visitor cookie)
views($post)->unique()->count();

// Record a new view
views($post)->record();

// Record a new view with session delay between views
views($post)->delayInSession(now()->addHours(2))->record();