Laravel visitors counter

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.


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


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