Laravel visitors counter

后端 未结 4 1624
情书的邮戳
情书的邮戳 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: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:

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

提交回复
热议问题