Laravel visitors counter

后端 未结 4 1610
情书的邮戳
情书的邮戳 2020-12-29 13:34

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

相关标签:
4条回答
  • 2020-12-29 13:50

    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.

    0 讨论(0)
  • 2020-12-29 13:51

    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();
    
    0 讨论(0)
  • 2020-12-29 13:53

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

    0 讨论(0)
  • 2020-12-29 14:06
    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

    0 讨论(0)
提交回复
热议问题