PHPackages                             ghdj/laravel-visitor-tracker - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Utility &amp; Helpers](/categories/utility)
4. /
5. ghdj/laravel-visitor-tracker

ActiveLibrary[Utility &amp; Helpers](/categories/utility)

ghdj/laravel-visitor-tracker
============================

A comprehensive visitor tracking package for Laravel applications with analytics, geolocation, and bot detection - zero external dependencies

v1.0.0(3mo ago)02MITPHPPHP ^8.1CI passing

Since Jan 25Pushed 3mo agoCompare

[ Source](https://github.com/GhDj/laravel-visitor-tracker)[ Packagist](https://packagist.org/packages/ghdj/laravel-visitor-tracker)[ Docs](https://github.com/ghdj/laravel-visitor-tracker)[ RSS](/packages/ghdj-laravel-visitor-tracker/feed)WikiDiscussions main Synced 1mo ago

READMEChangelogDependencies (10)Versions (3)Used By (0)

Laravel Visitor Tracker
=======================

[](#laravel-visitor-tracker)

[![Tests](https://github.com/ghdj/laravel-visitor-tracker/actions/workflows/tests.yml/badge.svg)](https://github.com/ghdj/laravel-visitor-tracker/actions/workflows/tests.yml)[![Latest Version on Packagist](https://camo.githubusercontent.com/b5bf88e2ae0e3386366a9d704506389b5b3288ef45f958019e5a2492f1fd352d/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f6768646a2f6c61726176656c2d76697369746f722d747261636b65722e737667)](https://packagist.org/packages/ghdj/laravel-visitor-tracker)[![License](https://camo.githubusercontent.com/4c50b23dd1dd4cca337cb141e6137d392c563de35e220b162c15bdb45fff7198/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f6c2f6768646a2f6c61726176656c2d76697369746f722d747261636b65722e737667)](https://packagist.org/packages/ghdj/laravel-visitor-tracker)

A comprehensive visitor tracking package for Laravel applications with analytics, geolocation, and bot detection.

**🚀 Zero External Dependencies** - Uses only Laravel's built-in features and native PHP for all functionality.

Features
--------

[](#features)

- 📊 **Comprehensive Tracking** - Track page views, unique visitors, and sessions
- 🤖 **Native Bot Detection** - Detect 100+ bots/crawlers without external packages
- 📱 **Native Device Detection** - Identify browsers, platforms, and device types using regex
- 🌍 **Geolocation** - Optional IP-based location tracking (using Laravel's HTTP client)
- 🔒 **GDPR Compliant** - GDPR Safe Mode for consent-free tracking, IP anonymization, DNT support
- ⚡ **Performance** - Queue support for async tracking, statistics caching
- 📈 **Rich Statistics** - Browser, platform, device, country, referrer analytics
- 🎯 **Flexible Exclusions** - Exclude paths, IPs, user agents, status codes
- 🔧 **Zero Dependencies** - Only uses Laravel's illuminate packages

Requirements
------------

[](#requirements)

- PHP 8.1+
- Laravel 10.x, 11.x, or 12.x

Installation
------------

[](#installation)

```
composer require ghdj/laravel-visitor-tracker
```

Publish the configuration file:

```
php artisan vendor:publish --tag="visitor-tracker-config"
```

Run the migrations:

```
php artisan migrate
```

Configuration
-------------

[](#configuration)

The configuration file is located at `config/visitor-tracker.php`. Key options include:

```
return [
    // Enable/disable tracking globally
    'enabled' => env('VISITOR_TRACKER_ENABLED', true),

    // Paths to exclude from tracking
    'exclude' => [
        'paths' => ['api/*', 'admin/*'],
        'methods' => ['OPTIONS', 'HEAD'],
        'status_codes' => [301, 302, 404, 500],
        'ips' => [],
        'user_agents' => [],
    ],

    // Bot tracking
    'bots' => [
        'track' => false,
        'detect' => true,
        'additional_patterns' => [], // Add custom bot patterns
    ],

    // Custom parser patterns
    'parser' => [
        'additional_browsers' => [], // Add custom browser patterns
        'additional_platforms' => [], // Add custom platform patterns
    ],

    // Geolocation (optional - uses Laravel HTTP client)
    'geolocation' => [
        'enabled' => env('VISITOR_TRACKER_GEOLOCATION', false),
        'provider' => 'ip-api', // ip-api (free), ipinfo, ipapi
    ],

    // GDPR compliance
    'privacy' => [
        'gdpr_safe_mode' => env('VISITOR_TRACKER_GDPR_SAFE', false),
        'anonymize_ip' => env('VISITOR_TRACKER_ANONYMIZE_IP', false),
        'respect_dnt' => true,
    ],

    // Data retention
    'retention' => [
        'days' => 90,
    ],

    // Queue for async tracking
    'queue' => [
        'enabled' => env('VISITOR_TRACKER_QUEUE', false),
    ],
];
```

Usage
-----

[](#usage)

### Middleware

[](#middleware)

Add the tracking middleware to your routes:

```
// In routes/web.php
Route::middleware(['track-visitor'])->group(function () {
    Route::get('/', [HomeController::class, 'index']);
    // ... more routes
});

// Or globally in bootstrap/app.php (Laravel 11)
->withMiddleware(function (Middleware $middleware) {
    $middleware->web(append: [
        \Ghdj\VisitorTracker\Middleware\TrackVisitor::class,
    ]);
})
```

### Using the Facade

[](#using-the-facade)

```
use Ghdj\VisitorTracker\Facades\VisitorTracker;

// Get statistics
$stats = VisitorTracker::stats();

// Total visitors (unique)
$totalVisitors = $stats->totalVisitors();

// Total page views
$totalPageViews = $stats->totalPageViews();

// Currently online visitors
$onlineNow = $stats->onlineVisitors();

// Today's visitors
$todayVisitors = $stats->todayVisitors();

// Visitors in last N days
$weeklyVisitors = $stats->visitorsLastDays(7);

// Most visited pages
$topPages = $stats->mostVisitedPages(10);

// Top referrers
$topReferrers = $stats->topReferrers(10);

// Browser statistics
$browsers = $stats->browserStats();

// Platform/OS statistics
$platforms = $stats->platformStats();

// Device type statistics
$devices = $stats->deviceStats();

// Country statistics (requires geolocation)
$countries = $stats->countryStats();

// Summary of all stats
$summary = $stats->summary();
```

### Using the Helper Function

[](#using-the-helper-function)

```
// Get tracker instance
$tracker = visitor();

// Get statistics
$stats = visitor()->stats()->summary();
$online = visitor_stats()->onlineVisitors();
```

### Blade Directives

[](#blade-directives)

```

    Total Visitors: @totalVisitors
    Total Page Views: @totalPageViews
    Online Now: @onlineVisitors
    Today's Visitors: @todayVisitors

```

### Working with Models

[](#working-with-models)

```
use Ghdj\VisitorTracker\Models\Visitor;
use Ghdj\VisitorTracker\Models\Visit;

// Get all visitors
$visitors = Visitor::all();

// Get online visitors
$online = Visitor::online()->get();

// Get visitors excluding bots
$humans = Visitor::excludeBots()->get();

// Get authenticated visitors only
$authenticated = Visitor::authenticated()->get();

// Get visitors from date range
$recent = Visitor::between(now()->subWeek(), now())->get();

// Get visits for a specific path
$homeVisits = Visit::path('/')->get();

// Get visits with referrers
$referred = Visit::withReferrer()->get();
```

### Using Native Services Directly

[](#using-native-services-directly)

```
use Ghdj\VisitorTracker\Services\UserAgentParser;
use Ghdj\VisitorTracker\Services\BotDetector;

// Parse user agent
$parser = new UserAgentParser();
$result = $parser->parse($request->userAgent());
// Returns: ['browser' => 'Chrome', 'browser_version' => '120.0', 'platform' => 'Windows', ...]

// Detect bots
$detector = new BotDetector();
$isBot = $detector->isBot($request->userAgent());
$botName = $detector->getBotName($request->userAgent());
$category = $detector->getBotCategory($request->userAgent()); // search_engine, social_media, ai_bot, etc.
```

### Adding Custom Patterns

[](#adding-custom-patterns)

```
// Add custom browser detection
$parser = new UserAgentParser();
$parser->addBrowserPatterns([
    'MyCustomBrowser' => '/MyCustomBrowser\/([0-9.]+)/',
]);

// Add custom bot detection
$detector = new BotDetector();
$detector->addPatterns(['mycustombot', 'anotherbot']);
$detector->addBotNames(['mycustombot' => 'My Custom Bot']);

// Or via config
// config/visitor-tracker.php
'parser' => [
    'additional_browsers' => [
        'MyBrowser' => '/MyBrowser\/([0-9.]+)/',
    ],
],
'bots' => [
    'additional_patterns' => ['mycustombot'],
],
```

### Listening to Events

[](#listening-to-events)

```
use Ghdj\VisitorTracker\Events\VisitorTracked;

// In EventServiceProvider or using Event facade
Event::listen(VisitorTracked::class, function (VisitorTracked $event) {
    $visitor = $event->visitor;
    $visit = $event->visit;

    // Custom logic here
    logger("New visit from {$visitor->ip} to {$visit->path}");
});
```

### Artisan Commands

[](#artisan-commands)

```
# Show visitor statistics
php artisan visitor-tracker:stats
php artisan visitor-tracker:stats --detailed

# Prune old data
php artisan visitor-tracker:prune
php artisan visitor-tracker:prune --days=30
php artisan visitor-tracker:prune --force
```

### Scheduling Data Pruning

[](#scheduling-data-pruning)

Add to your `routes/console.php` or scheduler:

```
use Illuminate\Support\Facades\Schedule;

Schedule::command('visitor-tracker:prune --force')->daily();
```

Dashboard Authentication
------------------------

[](#dashboard-authentication)

The dashboard is **always protected**. Choose an authentication method based on your site:

### Option 1: Token Authentication (Sites Without Login)

[](#option-1-token-authentication-sites-without-login)

For sites without user authentication, use a secret token:

```
# Add to your .env file (NEVER commit this!)
VISITOR_TRACKER_TOKEN=your-secret-token-here
```

Enable the dashboard in `config/visitor-tracker.php`:

```
'dashboard' => [
    'enabled' => true,
    'token' => env('VISITOR_TRACKER_TOKEN'),
    'middleware' => ['web'], // No 'auth' needed
],
```

Access the dashboard via:

- **URL**: `/admin/visitor-tracker?token=your-secret-token-here`
- **Header**: `X-Visitor-Tracker-Token: your-secret-token-here`
- **Bearer**: `Authorization: Bearer your-secret-token-here`

### Option 2: Laravel Auth (Sites With Login)

[](#option-2-laravel-auth-sites-with-login)

For sites with user authentication:

```
'dashboard' => [
    'enabled' => true,
    'middleware' => ['web', 'auth'],
],
```

### Option 3: Gate Authorization (Role-Based Access)

[](#option-3-gate-authorization-role-based-access)

For admin-only access with Laravel Gates:

```
// In AuthServiceProvider
Gate::define('view-visitor-stats', function ($user) {
    return $user->is_admin;
});

// In config/visitor-tracker.php
'dashboard' => [
    'enabled' => true,
    'middleware' => ['web', 'auth'],
    'gate' => 'view-visitor-stats',
],
```

Geolocation Providers
---------------------

[](#geolocation-providers)

All providers use Laravel's built-in HTTP client - no external packages required.

### ip-api.com (Free, No API Key)

[](#ip-apicom-free-no-api-key)

```
VISITOR_TRACKER_GEOLOCATION=true
VISITOR_TRACKER_GEO_PROVIDER=ip-api
```

### ipinfo.io

[](#ipinfoio)

```
VISITOR_TRACKER_GEOLOCATION=true
VISITOR_TRACKER_GEO_PROVIDER=ipinfo
VISITOR_TRACKER_GEO_API_KEY=your_api_key
```

Queue Support
-------------

[](#queue-support)

For high-traffic sites, enable queue processing:

```
VISITOR_TRACKER_QUEUE=true
VISITOR_TRACKER_QUEUE_CONNECTION=redis
VISITOR_TRACKER_QUEUE_NAME=tracking
```

GDPR Safe Mode
--------------

[](#gdpr-safe-mode)

To track **anonymous aggregate statistics without requiring user consent**, enable GDPR Safe Mode:

```
VISITOR_TRACKER_GDPR_SAFE=true
```

When enabled, the following personal data is **NOT collected**:

DataStatusNotesIP Address❌ Not storedNot even anonymizedUser ID❌ Not storedNo link to authenticated usersPersistent Cookie❌ Not usedSession-only identificationFull User Agent❌ Not storedOnly parsed for aggregate statsCity / Region❌ Not storedOnly country-level locationCoordinates❌ Not storedNo lat/long**What IS still collected** (anonymous, aggregate data):

DataPurposePage view countsTraffic analyticsBrowser nameChrome, Firefox, etc.Platform nameWindows, macOS, etc.Device typeMobile, desktop, tabletCountryBroad geographic distributionReferrer domainTraffic sources```
// Check if GDPR safe mode is enabled
if (VisitorTracker::isGdprSafeMode()) {
    // No personal data being collected
}
```

Detected Browsers
-----------------

[](#detected-browsers)

Chrome, Firefox, Safari, Edge, Opera, Brave, Vivaldi, Samsung Browser, UC Browser, Yandex, IE, and more.

Detected Platforms
------------------

[](#detected-platforms)

Windows (XP through 11), macOS, iOS, Android, Linux, Ubuntu, Chrome OS, FreeBSD.

Detected Bots
-------------

[](#detected-bots)

100+ bot patterns including:

- **Search Engines**: Google, Bing, Yahoo, DuckDuckGo, Baidu, Yandex
- **Social Media**: Facebook, Twitter, LinkedIn, Pinterest, Slack, Discord
- **AI/LLM**: GPTBot, ClaudeBot, Anthropic, CCBot, Perplexity
- **SEO Tools**: Ahrefs, SEMrush, Moz, Majestic
- **Monitoring**: UptimeRobot, Pingdom, DataDog, New Relic
- **HTTP Clients**: cURL, Wget, Python Requests, Postman, Axios

Testing
-------

[](#testing)

```
composer test
```

Code Quality
------------

[](#code-quality)

```
# Run code style fixer
composer format

# Run static analysis
composer analyse
```

Why Zero Dependencies?
----------------------

[](#why-zero-dependencies)

- **Smaller footprint** - No additional packages to install or maintain
- **Better performance** - Native regex is fast and efficient
- **Full control** - Easily extend patterns via configuration
- **Security** - Less attack surface, no supply chain concerns
- **Reliability** - Only depends on Laravel core packages

Changelog
---------

[](#changelog)

Please see [CHANGELOG](CHANGELOG.md) for more information on what has changed recently.

Contributing
------------

[](#contributing)

Contributions are welcome! Please feel free to submit a Pull Request.

License
-------

[](#license)

The MIT License (MIT). Please see [License File](LICENSE) for more information.

###  Health Score

35

—

LowBetter than 79% of packages

Maintenance80

Actively maintained with recent releases

Popularity2

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity44

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Unknown

Total

1

Last Release

107d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/336b841c0b2f83b075cc33293657d5e0fc070f471d684a7f8d92e5e8270a9274?d=identicon)[GhDj](/maintainers/GhDj)

---

Top Contributors

[![GhDj](https://avatars.githubusercontent.com/u/2568401?v=4)](https://github.com/GhDj "GhDj (2 commits)")

---

Tags

analyticsbot-detectiongdprlaravelprivacystatisticsvisitor-trackingzero-dependencylaravelgeolocationtrackingvisitoranalyticsstatisticsbot-detectionzero-dependency

###  Code Quality

TestsPest

Static AnalysisPHPStan

Code StyleLaravel Pint

Type Coverage Yes

### Embed Badge

![Health badge](/badges/ghdj-laravel-visitor-tracker/health.svg)

```
[![Health](https://phpackages.com/badges/ghdj-laravel-visitor-tracker/health.svg)](https://phpackages.com/packages/ghdj-laravel-visitor-tracker)
```

###  Alternatives

[spatie/laravel-enum

Laravel Enum support

3655.4M31](/packages/spatie-laravel-enum)[psalm/plugin-laravel

Psalm plugin for Laravel

3274.9M308](/packages/psalm-plugin-laravel)[aedart/athenaeum

Athenaeum is a mono repository; a collection of various PHP packages

255.2k](/packages/aedart-athenaeum)[dragon-code/pretty-routes

Pretty Routes for Laravel

10058.7k4](/packages/dragon-code-pretty-routes)[cornford/googlitics

An easy way to integrate Google Analytics with Laravel.

3310.2k](/packages/cornford-googlitics)[bjuppa/laravel-blog

Add blog functionality to your Laravel project

483.3k2](/packages/bjuppa-laravel-blog)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
