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:
//stats
$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);
if(!$check_if_exists)
{
DB::table('visitor')->insert(array('ip' => $_SERVER['REMOTE_ADDR'], 'hits' => '1', 'visit_date' => $date));
}else{
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:
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?
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 intovisit_date (date)
andvisit_time (time)
columns, then create anid
column to be the primary key. Lastly, setip + 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:
Now you should be able to do what you want by just calling this:
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: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:
In terms of where to bootstrap this, the
App::before()
filter sounds like a good candidate: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.
In laravel 5.7 it required parent::boot() otherwise it will show Undefined index: App\Tracker https://github.com/laravel/framework/issues/25455
Thanks to @Joe for helping me fulley out!
@Martin, you also thanks, but the scripts of @Joe worked for my problem.
The solution:
Inside my App::before();
And a new class:
Named 'tracker' :)