我正在尝试在 Laravel 中建立一个访客计数器....
I'm trying to build a visitors counter in Laravel....
我不知道将代码放入其中以便加载到每个页面上的最佳位置是什么……但我将它放在 routes.php 中……
I don't know what the best place is to put the code inside so that it loads on EVERY page... But I putted it inside of the routes.php....
我想我最好把它放在 basecontroller 里面?
I think I'll better place it inside of basecontroller?
但是好吧,我的代码现在看起来像这样:
But okay, My code looks like this now:
//stats
$date = new DateTime;
$check_if_exists = DB::table('visitor')->where('ip', $_SERVER['REMOTE_ADDR'])->first();
$get_visit_day = DB::table('visitor')->select('visit_date')->where('ip', $_SERVER['REMOTE_ADDR'])->first();
$value = date_create($get_visit_day->visit_date);
if(!$check_if_exists)
{
DB::table('visitor')->insert(array('ip' => $_SERVER['REMOTE_ADDR'], 'hits' => '1', 'visit_date' => $date));
}else{
DB::table('visitor')->where('ip', $_SERVER['REMOTE_ADDR'])->increment('hits');
}
$value = date_create($get_visit_day->visit_date);
if ($check_if_exists && date_format($value, 'd') != date('d')) {
DB::table('visitor')->insert(array('ip' => $_SERVER['REMOTE_ADDR'], 'hits' => '1', 'visit_date' => $date));
}
这很好,但问题是,我的数据库列总是添加一个新值.
That works fine, but the problem is, my database columns always add a new value.
这是我的数据库:
来自表访客".
它不断添加一个新的IP,hit和visit_date...
It keeps adding a new IP, hit and visit_date...
如何仅更新今天(当天)的点击数,如果过了一天,设置新的 IP 值并在该列中计数?
How is it possible to just update the hits from today (the day) and if the day is passed, to set a new IP value and count in that column?
我不是 100% 确定这一点,但你应该能够做这样的事情.它未经测试,可能有更优雅的方式来做,但它是您的起点.
I'm not 100% sure on this, but you should be able to do something like this. It's not tested, and there may be a more elegant way to do it, but it's a starting point for you.
换桌
将 visit_date (datetime)
列更改为 visit_date (date)
和 visit_time (time)
列,然后创建 id
列作为主键.最后,将 ip + date
设置为唯一键,以确保您不能在一天内输入两次相同的 IP.
Change the visit_date (datetime)
column into visit_date (date)
and visit_time (time)
columns, then create an id
column to be the primary key. Lastly, set ip + date
to be a unique key to ensure you can't have the same IP entered twice for one day.
创建 Eloquent 模型
这只是为了方便:为表创建一个 Eloquent 模型,这样您就不必一直使用 Fluent(查询构建器):
This is just for ease: make an Eloquent model for the table so you don't have to use Fluent (query builder) all the time:
class Tracker extends Eloquent {
public $attributes = [ 'hits' => 0 ];
protected $fillable = [ 'ip', 'date' ];
protected $table = 'table_name';
public static function boot() {
// Any time the instance is updated (but not created)
static::saving( function ($tracker) {
$tracker->visit_time = date('H:i:s');
$tracker->hits++;
} );
}
public static function hit() {
static::firstOrCreate([
'ip' => $_SERVER['REMOTE_ADDR'],
'date' => date('Y-m-d'),
])->save();
}
}
现在你应该可以通过调用这个来做你想做的事了:
Now you should be able to do what you want by just calling this:
Tracker::hit();
这篇关于Laravel 访客柜台的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!