Laravel visitors counter

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

提交回复
热议问题