Laravel游客柜台 [英] Laravel visitors counter
问题描述
我正在尝试在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,匹配和访问日期...
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模型,这样您就不必一直使用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游客柜台的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!