Laravel visitors counter

 ̄綄美尐妖づ 提交于 2019-12-18 13:16:10

问题


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:

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?


回答1:


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();



回答2:


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.




回答3:


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' :)




回答4:


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



来源:https://stackoverflow.com/questions/29694372/laravel-visitors-counter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!