Laravel visitors counter

2019-02-06 17:42发布

I'm trying to build a visitors counter in Laravel....

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....

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.

So this is my database: With the table 'visitor'

From the table 'visitor'.

It keeps adding a new IP, hit and visit_date...

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?

4条回答
不美不萌又怎样
2楼-- · 2019-02-06 18:22

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.

Change the table

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.

Create an Eloquent model

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();
查看更多
霸刀☆藐视天下
3楼-- · 2019-02-06 18:23

Looking at your code and reading your description, I’m assuming you want to calculate number of hits from an IP address per day. You could do this using Eloquent’s updateOrNew() method:

$ip = Request::getClientIp();
$visit_date = Carbon::now()->toDateString();

$visitor = Visitor::findOrNew(compact('ip', 'visit_date'));
$visitor->increment('hits');

However, I would add this to a queue so you’re not hitting the database on every request and incrementing your hit count can be done via a background process:

Queue::push('RecordVisit', compact('ip', 'visit_date'));

In terms of where to bootstrap this, the App::before() filter sounds like a good candidate:

App::before(function($request)
{
    $ip = $request->getClientIp();
    $visit_date = Carbon::now()->toDateString();

    Queue::push('RecordVisit', compact('ip', 'visit_date'));
);

You could go one step further by listening for this event in a service provider and firing your queue job there, so that your visit counter is its own self-contained component and can be added or removed easily from this and any other projects.

查看更多
一夜七次
4楼-- · 2019-02-06 18:24
public $attributes = ['hits' => 0];

protected $fillable = ['ip', 'date'];

public $timestamps = false;

protected $table = 'trackers';

public static function boot() {
    // When a new instance of this model is created...
    parent::boot();
    static::creating(function ($tracker) {
        $tracker->hits = 0;
    } );

    // Any time the instance is saved (create OR update)
    static::saving(function ($tracker) {
        $tracker->visit_date = date('Y-m-d');
        $tracker->visit_time = date('H:i:s');
        $tracker->hits++;
    } );
}

// Fill in the IP and today's date
public function scopeCurrent($query) {
    return $query->where('ip', $_SERVER['REMOTE_ADDR'])
                 ->where('date', date('Y-m-d'));
}

public static function hit() {
   /* $test= request()->server('REMOTE_ADDR');
    echo $test;
    exit();*/
    static::firstOrCreate([
              'ip'   => $_SERVER['REMOTE_ADDR'],

              'date' => date('Y-m-d'),
             // exit()
          ])->save();

}

In laravel 5.7 it required parent::boot() otherwise it will show Undefined index: App\Tracker https://github.com/laravel/framework/issues/25455

查看更多
Luminary・发光体
5楼-- · 2019-02-06 18:37

Thanks to @Joe for helping me fulley out!

@Martin, you also thanks, but the scripts of @Joe worked for my problem.

The solution:

Tracker::hit();

Inside my App::before();

And a new class:

<?php

class Tracker Extends Eloquent {

    public $attributes = ['hits' => 0];

    protected $fillable = ['ip', 'date'];

    public $timestamps = false;

    protected $table = 'visitor';

    public static function boot() {
        // When a new instance of this model is created...
        static::creating(function ($tracker) {
            $tracker->hits = 0;
        } );

        // Any time the instance is saved (create OR update)
        static::saving(function ($tracker) {
            $tracker->visit_date = date('Y-m-d');
            $tracker->visit_time = date('H:i:s');
            $tracker->hits++;
        } );
    }

    // Fill in the IP and today's date
    public function scopeCurrent($query) {
        return $query->where('ip', $_SERVER['REMOTE_ADDR'])
                     ->where('date', date('Y-m-d'));
    }

    public static function hit() {
        static::firstOrCreate([
                  'ip'   => $_SERVER['REMOTE_ADDR'],
                  'date' => date('Y-m-d'),
              ])->save();
    }
}

Named 'tracker' :)

查看更多
登录 后发表回答