Robin R Robin R - 1 year ago 151
MySQL Question

Laravel visitors counter

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:


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


DB::table('visitor')->insert(array('ip' => $_SERVER['REMOTE_ADDR'], 'hits' => '1', 'visit_date' => $date));


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:
With the table 'visitor'

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?

Joe Joe
Answer Source

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');
        } );

    public static function hit() {
                  'ip'   => $_SERVER['REMOTE_ADDR'],
                  'date' => date('Y-m-d'),


Now you should be able to do what you want by just calling this: