Laravel Stats Tracker


Why?
Storing user tracking information, on indexed and normalized database tables, wastes less disk space and ease the extract of valuable information about your application and business.
Usage
As soon as you install and enable it, Tracker will start storing all information you tell it to, then you can in your application use the Tracker Facade to access everything. Here are some of the methods and relatioships available:


How you write your won method :


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

if you want to call this hit method use Tracker ::hit().
Current Session/Visitor
$visitor = Tracker::currentSession();
Most of those methods return an Eloquent model or collection, so you can use not only its attributes, but also relational data:
var_dump( $visitor->client_ip );

var_dump( $visitor->device->is_mobile );

var_dump( $visitor->device->platform );

var_dump( $visitor->geoIp->city );

var_dump( $visitor->language->preference );
Sessions (visits)
$sessions = Tracker::sessions(60 * 24); // get sessions (visits) from the past day
foreach ($sessions as $session)
{
    var_dump( $session->user->email );

    var_dump( $session->device->kind . ' - ' . $session->device->platform );

    var_dump( $session->agent->browser . ' - ' . $session->agent->browser_version );

    var_dump( $session->geoIp->country_name );

    foreach ($session->session->log as $log)
    {
         var_dump( $log->path );
    }
}
Online Users
Brings all online sessions (logged and unlogged users)
$users = Tracker::onlineUsers(); // defaults to 3 minutes
Users
$users = Tracker::users(60 * 24);
User Devices
$users = Tracker::userDevices(60 * 24, $user->id);
Events
$events = Tracker::events(60 * 24);
Errors
$errors = Tracker::errors(60 * 24);
PageViews summary
$pageViews = Tracker::pageViews(60 * 24 * 30);
PageViews By Country summary
$pageViews = Tracker::pageViewsByCountry(60 * 24);
Filter range
You can send timestamp ranges to those methods using the Minutes class:
$range = new Minutes();

$range->setStart(Carbon::now()->subDays(2));

$range->setEnd(Carbon::now()->subDays(1));

Tracker::userDevices($range);
Routes By Name
Having a route of
Route::get('user/{id}', ['as' => 'user.profile', 'use' => 'UsersController@profile']);
You can use this method to select all hits on that particular route and count them using Laravel:
return Tracker::logByRouteName('user.profile')
        ->where(function($query)
        {
            $query
                ->where('parameter', 'id')
                ->where('value', 1);
        })
        ->count();
And if you need count how many unique visitors accessed that route, you can do:
return Tracker::logByRouteName('tracker.stats.log')
        ->where(function($query)
        {
            $query
                ->where('parameter', 'uuid')
                ->where('value', '8b6faf82-00f1-4db9-88ad-32e58cfb4f9d');
        })
        ->select('tracker_log.session_id')
        ->groupBy('tracker_log.session_id')
        ->distinct()
        ->count('tracker_log.session_id');

Blade Views
The views above are available in this package, but you need to install the sb-admin panel on your public folder, please look at the instructions below.
How data is stored
All tables are prefixed by tracker_, and here's an extract of some of them, showing columns and contents:
devices
+----+----------+-------------+-------------+------------------+-----------+
| id | kind     | model       | platform    | platform_version | is_mobile |
+----+----------+-------------+-------------+------------------+-----------+
| 1  | Computer | unavailable | Windows 8   |                  |           |
| 2  | Tablet   | iPad        | iOS         | 7.1.1            | 1         |
| 3  | Computer | unavailable | Windows XP  |                  |           |
| 5  | Computer | unavailable | Other       |                  |           |
| 6  | Computer | unavailable | Windows 7   |                  |           |
| 7  | Computer | unavailable | Windows 8.1 |                  |           |
| 8  | Phone    | iPhone      | iOS         | 7.1              | 1         |
+----+----------+-------------+-------------+------------------+-----------+
languages
+----+------------+----------------+
| id | preference | language_range |
+----+------------+----------------+
| 1  | en         | ru=0.8,es=0.5  |
| 2  | es         | en=0.7,ru=0.3  |
| 3  | ru         | en=0.5,es=0.5  |
+----+------------+----------------+
domains
+----+--------------------------+
| id | name                     |
+----+--------------------------+
| 1  | antoniocarlosribeiro.com |
+----+--------------------------+

events
+----+------------------------------------------------+
| id | name                                           |
+----+------------------------------------------------+
| 1  | illuminate.log                                 |
| 2  | router.before                                  |
| 3  | router.matched                                 |
| 4  | auth.attempt                                   |
| 5  | auth.login                                     |
| 6  | composing: admin.tracker.index                 |
| 7  | creating: admin.tracker._partials.menu         |
| 8  | composing: admin.tracker._partials.menu        |
| 9  | creating: admin.layout                         |
| 10 | composing: admin.layout                        |
| 11 | creating: admin._partials.mainMenu             |
| 12 | composing: admin._partials.mainMenu            |
| 13 | creating: admin._partials.messages             |
| 14 | composing: admin._partials.messages            |
| 15 | creating: global._partials.google-analytics    |
| 16 | composing: global._partials.google-analytics   |
+----+------------------------------------------------+
log
+-----+------------+---------+----------+--------+---------------+---------+-----------+---------+------------+----------+
| id  | session_id | path_id | query_id | method | route_path_id | is_ajax | is_secure | is_json | wants_json | error_id |
+-----+------------+---------+----------+--------+---------------+---------+-----------+---------+------------+----------+
| 1   | 1          | 1       |          | GET    | 1             |         | 1         |         |            |          |
| 2   | 1          | 2       |          | GET    | 2             |         | 1         |         |            |          |
| 3   | 1          | 3       |          | GET    | 3             |         | 1         |         |            |          |
| 4   | 1          | 3       |          | POST   | 4             |         | 1         |         |            |          |
+-----+------------+---------+----------+--------+---------------+---------+-----------+---------+------------+----------+
paths
+----+--------------------------------------------------------+
| id | path                                                   |
+----+--------------------------------------------------------+
| 1  | /                                                      |
| 2  | admin                                                  |
| 3  | login                                                  |
| 4  | admin/languages                                        |
| 5  | admin/tracker                                          |
| 6  | admin/pages                                            |
| 7  | jmx-console                                            |
| 8  | manager/html                                           |
| 9  | administrator                                          |
| 10 | joomla/administrator                                   |
| 11 | cms/administrator                                      |
| 12 | Joomla/administrator                                   |
| 13 | phpmyadmin                                             |
| 14 | phpMyAdmin                                             |
| 15 | mysql                                                  |
| 16 | sql                                                    |
| 17 | myadmin                                                |
| 18 | webdav                                                 |
+----+--------------------------------------------------------+
route_paths
+----+----------+--------------------------------------------------------+
| id | route_id | path                                                   |
+----+----------+--------------------------------------------------------+
| 1  | 1        | /                                                      |
| 2  | 2        | admin                                                  |
| 3  | 3        | login                                                  |
| 4  | 4        | login                                                  |
| 5  | 5        | admin/languages                                        |
| 6  | 6        | admin/tracker                                          |
| 7  | 7        | admin/pages                                            |
+----+----------+--------------------------------------------------------+
routes
+----+--------------------------------------+----------------------------------------------------------+
| id | name                                 | action                                                   |
+----+--------------------------------------+----------------------------------------------------------+
| 1  | home                                 | ACR\Controllers\Home@index                               |
| 2  | admin                                | ACR\Controllers\Admin\Admin@index                        |
| 3  | login.form                           | ACR\Controllers\Logon@form                               |
| 4  | login.do                             | ACR\Controllers\Logon@login                              |
| 5  | admin.languages.index                | ACR\Controllers\Admin\Languages@index                    |
| 6  | admin.tracker.index                  | ACR\Controllers\Admin\Tracker@index                      |
| 7  | admin.pages.index                    | ACR\Controllers\Admin\Pages@index                        |
| 8  | admin.tracker.log                    | ACR\Controllers\Admin\Tracker@log                        |
| 9  | technology                           | ACR\Controllers\Technology@index                         |
| 10 | technology.articles.show             | ACR\Controllers\Technology@show                          |
| 11 | language.select                      | ACR\Controllers\Language@select                          |
| 12 | admin.tracker.summary                | ACR\Controllers\Admin\Tracker@summary                    |
| 13 | admin.tracker.api.pageviews          | ACR\Controllers\Admin\Tracker@apiPageviews               |
| 14 | admin.tracker.api.pageviewsbycountry | ACR\Controllers\Admin\Tracker@apiPageviewsByCountry      |
| 15 | admin.pages.create                   | ACR\Controllers\Admin\Pages@create                       |
| 16 | api.markdown                         | ACR\Controllers\Api@markdown                             |
| 17 | admin.pages.store                    | ACR\Controllers\Admin\Pages@store                        |
| 18 | bio                                  | ACR\Controllers\StaticPages@show                         |
| 19 | logout.do                            | ACR\Controllers\Logon@logout                             |
| 20 | admin.tracker.index                  | ACR\Controllers\Admin\UsageTracker@index                 |
| 21 | admin.tracker.api.pageviewsbycountry | ACR\Controllers\Admin\UsageTracker@apiPageviewsByCountry |
| 22 | admin.tracker.api.pageviews          | ACR\Controllers\Admin\UsageTracker@apiPageviews          |
+----+--------------------------------------+----------------------------------------------------------+
Manually log things
If your application has special needs, you can manually log things like:
Events
Tracker::trackEvent(['event' => 'cart.add']);
Tracker::trackEvent(['event' => 'cart.add', 'object' => 'App\Cart\Events\Add']);
Routes
Tracker::trackVisit(
    [
        'name' => 'my.dynamic.route.name',
        'action' => 'MyDynamic@url'
    ],
    ['path' => 'my/dynamic/url']
);
Requirements
  • Laravel 5+
  • PHP 5.3.7+
  • Package "geoip/geoip":"~1.14" or "geoip2/geoip2":"~2.0" (If you are planning to store Geo IP information)
For Laravel 4+ please use version 2.0.10.
Installing
Require the tracker package by executing the following command in your command line:
composer require pragmarx/tracker
Add the service provider to your app/config/app.php:
'PragmaRX\Tracker\Vendor\Laravel\ServiceProvider',
Add the alias to the facade on your app/config/app.php:
'Tracker' => 'PragmaRX\Tracker\Vendor\Laravel\Facade',
Publish tracker configuration:
Laravel 4
php artisan config:publish pragmarx/tracker
Laravel 5
php artisan vendor:publish --provider=PragmaRX\\Tracker\\Vendor\\Laravel\\ServiceProvider
Enable the Middleware (Laravel 5)
'use_middleware' => true,
Add the Middleware to Laravel Kernel (Laravel 5)
Open the file app/Http/Kernel.php and add the following to your web middlewares:
\PragmaRX\Tracker\Vendor\Laravel\Middlewares\Tracker::class,
Enable Tracker in your config.php (Laravel 4) or tracker.php (Laravel 5)
'enabled' => true,
Publish the migration
php artisan tracker:tables
This is only needed if you are on Laravel 4, because vendor:publish does it for you in Laravel 5.





Create a database connection for it on your config/database.php
'connections' => [
    'mysql' => [
        ...
    ],
   
    'tracker' => [
         'driver'   => '...',
         'host'     => '...',
         'database' => ...,
        'strict' => false,    // to avoid problems on some MySQL installs
         ...
    ],
],
Migrate it
If you have set the default connection to tracker, you can
php artisan migrate
Otherwise you'll have to
php artisan migrate --database=tracker

Everything Is Disabled By Default
Tracker has a lot of logging options, but you need to decide what you want to log. Starting by enabling this one:
'log_enabled' => true,
It is responsible for logging page hits and sessions, basically the client IP address.
Multiple authentication drivers
You just have to all your auth IOC bidings to the array:
'authentication_ioc_binding' => ['auth', 'admin'],
Stats Panel
To use the stats panel on your website you'll need to download the sb-admin 2 sources to your public folder:
git clone https://github.com/BlackrockDigital/startbootstrap-sb-admin-2.git public/templates/sb-admin-2
cd public/templates/sb-admin-2
git checkout tags/v3.3.7+1
git checkout -b v3.3.7+1
And enabled in your config file:
'stats_panel_enabled' => true,
Set the web middleware for stats routes (Laravel 5)
'stats_routes_middleware' => 'web',
Only admins can view the stats, so if you don't have an is_admin attribute on your user model, you'll have to add one:
public function getIsAdminAttribute()
    {
        return true;
    }
It can be 'admin', 'is_admin', 'root' or 'is_root'.



Comments

  1. hello after installing laravel stats Panel and using url stats I have a problem retrieving the information
    I get this "
    tracker :: tracker.visits "not the simple name can you help me please

    ReplyDelete

Post a Comment

Popular posts from this blog

Laravel 5 Chart example using Charts Package

PHPMyBackup - A PHP MySQL differential backup script