A comprehensive Laravel package providing privacy-compliant web analytics functionality for content management systems.
This package provides a complete analytics solution for Laravel applications, with a strong focus on privacy compliance and GDPR adherence. It offers detailed visitor tracking, real-time statistics, and an intuitive admin dashboard widget without relying on external services. The package is designed to be lightweight, extensible, and fully integrated with the Core CMS ecosystem.
- ✅ Privacy-compliant visitor tracking with IP anonymization
- ✅ Real-time analytics dashboard with interactive charts
- ✅ Bot detection and filtering capabilities
- ✅ GDPR-compliant data collection with consent management
- ✅ Custom event tracking system
- ✅ Page visit time tracking with session management
- ✅ Browser, platform, and device analytics
- ✅ Referrer analysis with data sanitization
- ✅ Automatic cache management for performance
- ✅ Multi-language support (EN/FR included)
- ✅ RESTful API endpoints with rate limiting
- ✅ Single Page Application (SPA) tracking support
- PHP ^8.1
- Laravel ^12.0
- netauratech/core-cms ^1.0
composer require netauratech/analytics-manager- Clone the repository into your Laravel project
- Add the dependency to your
composer.json - Run
composer install
The service provider is automatically registered thanks to Laravel's automatic discovery. If you want to register it manually, add it to config/app.php:
'providers' => [
// ...Netauratech\AnalyticsManager\AnalyticsManagerServiceProvider::class,
],Run the migrations to create the analytics database tables:
php artisan migrateThis will create the visits table with the following structure:
- Visit tracking data (URL, referrer, timestamps)
- Privacy-compliant user identification (hashed IP addresses)
- Browser and device information
- Custom data storage (JSON format)
- Comprehensive indexing for performance
The package automatically registers a tracking script that integrates with your frontend. The script includes:
- GDPR consent management integration
- Single Page Application (SPA) support
- Automatic event tracking capabilities
- Time-on-page measurement
The tracking script is automatically included via the Core CMS asset manager. Make sure to initialize tracking in your frontend:
// The script automatically initializes when CSRF token is available// and GDPR consent is givenwindow.addEventListener("csrf-ready",function(event){// Tracking automatically starts if consent is available});// For GDPR compliancewindow.addEventListener('gdpr:consent-given',function(){// Tracking starts automatically after consent});Track custom events programmatically:
// Track custom eventswindow.trackEvent('button_click',{button_id: 'signup-btn',location: 'header'});// Track external link clicks (automatic)// Track scroll depth (automatic: 25%, 50%, 75%, 90%)// Track element clicks with data-track attribute (automatic)The package automatically adds an analytics widget to your Core CMS admin dashboard. The widget provides:
- Total visits and unique visitors
- Page views and bounce rate
- Time-based filtering (7 days, 30 days, all time)
- URL-specific analytics
- Daily visits line chart
- Daily unique visitors chart
- Browser distribution pie chart
- Platform distribution pie chart
- Device type distribution pie chart
- Most visited pages ranking
- Visit counts per page
- Direct navigation to page analytics
The package provides RESTful API endpoints for analytics tracking:
POST /api/track-visitContent-Type: application/json
{
"url": "/current-page",
"referer": "https://example.com/previous-page",
"screen_width": 1920,
"screen_height": 1080,
"utm_source": "google",
"utm_medium": "cpc",
"utm_campaign": "summer2024"
}POST /api/track-timeContent-Type: application/json
{
"visit_id": 123,
"time_spent": 45,
"url": "/current-page"
}POST /api/track-eventContent-Type: application/json
{
"visit_id": 123,
"event": "video_play",
"url": "/current-page",
"data": {
"video_title": "Product Demo",
"duration": "2:30"
}
}// IP addresses are automatically hashed with daily saltprivatefunctionhashIP(string$ipAddress): string
{
$salt = config('app.key') . date('Y-m-d');
// IPv4 anonymization: 192.168.1.1 → 192.xxx.xxx.xxx// IPv6 anonymization: full address → ipv6.xxxreturnhash('sha256', $ipAddress . $salt);
}// Referrer URLs are automatically sanitizedprivatefunctionsanitizeReferer(?string$referer): ?string
{
// Only scheme, domain, and path are retained// Query parameters and fragments are removed// Length is limited to 500 characters
}// Comprehensive bot detectionprivatefunctionisBot(?string$userAgent): bool
{
// Detects: googlebot, bingbot, crawlers, spiders// Identifies: curl, wget, automated tools// Filters: empty or suspicious user agents
}useNetauratech\AnalyticsManager\Models\Visit;
// Get overall statistics$stats = Visit::getQuickStats('7_days');
// Returns: total_visits, unique_visitors, pages_visited, bounce_rate// Get statistics for specific URL$stats = Visit::getQuickStats('30_days', '/specific-page');// Get visits for specific period$visits = Visit::period('7_days')
->excludeBots()
->with('custom_data')
->get();
// Get unique visitors$uniqueVisitors = Visit::period('30_days')
->excludeBots()
->distinct('ip_hash')
->count('ip_hash');
// Browser statistics$browsers = Visit::selectRaw('browser, COUNT(*) as count')
->period('7_days')
->excludeBots()
->groupBy('browser')
->orderByDesc('count')
->get();// Period filtering
Visit::period('7_days'); // Last 7 days
Visit::period('30_days'); // Last 30 days
Visit::period('today'); // Today only
Visit::period('this_week'); // Current week
Visit::period('this_month'); // Current month// URL filtering
Visit::forUrl('/specific-page');
// Bot filtering
Visit::excludeBots();
// Unique visitors only
Visit::uniqueOnly();$visit = Visit::find(1);
// Device type checks$visit->isMobile(); // boolean$visit->isTablet(); // boolean $visit->isDesktop(); // boolean// Display names$visit->getBrowserDisplayName(); // "Google Chrome"$visit->getPlatformDisplayName(); // "Windows"// Referrer analysis$visit->getRefererDomain(); // "google.com"$visit->isDirectVisit(); // boolean// Date formatting$visit->getFormattedVisitDate(); // "19 Sep 2025 14:30"The package includes intelligent caching to ensure optimal performance:
// Cache keys are automatically generated and managed$cacheKey = md5(json_encode(['period' => $period, 'url' => $url]));
// Cache is automatically invalidated when new visits are recordedprivatefunctioninvalidateAnalyticsCache(): void
{
// Clears relevant cache entries for all periods and categories
}// Uses Laravel's default cache store$cache = Cache::store(config('cache.default'));
// 15-minute TTL for dashboard data$ttl = now()->addMinutes(15);useNetauratech\AnalyticsManager\Models\Visit;
class CustomVisit extends Visit
{
// Add custom methods or override existing onespublicfunctiongetCustomMetric(): float
{
// Your custom logic here
}
}useNetauratech\AnalyticsManager\Widgets\AnalyticsWidget;
class CustomAnalyticsWidget extends AnalyticsWidget
{
publicfunctionrender(): View
{
// Get base data$data = parent::render()->getData();
// Add your custom data$data['customMetric'] = $this->getCustomMetric();
returnview('your-package::custom-analytics', $data);
}
privatefunctiongetCustomMetric()
{
// Your custom analytics logic
}
}// In your service provideruseNetauratech\CoreCms\Services\AssetManager;
publicfunctionboot(AssetManager$assetManager)
{
$assetManager->registerView('your-package::custom-tracking');
}Create custom-tracking.blade.php:
<script>document.addEventListener('DOMContentLoaded',function(){// Custom tracking logicdocument.querySelectorAll('.track-download').forEach(element=>{element.addEventListener('click',function(){window.trackEvent('file_download',{file_name: this.getAttribute('data-file'),file_type: this.getAttribute('data-type')});});});});</script>src/
├── Http/
│ └── Controllers/
│ └── Api/
│ └── AnalyticsController.php # Main API controller
├── Models/
│ └── Visit.php # Visit model with scopes
├── Widgets/
│ └── AnalyticsWidget.php # Dashboard widget
├── database/
│ └── migrations/
│ └── 2025_09_13_000000_create_visits_table.php
├── lang/ # Multi-language support
│ ├── en/
│ │ └── admin.php
│ └── fr/
│ └── admin.php
├── resources/
│ └── views/
│ ├── script.blade.php # Frontend tracking script
│ └── widgets/
│ └── analytics.blade.php # Dashboard widget view
├── routes/
│ └── api.php # API routes definition
└── AnalyticsManagerServiceProvider.php # Main service provider
Tracks a website visit with comprehensive data collection:
- Browser and device detection
- IP anonymization and hashing
- Bot detection and filtering
- Unique visitor identification
- UTM parameter extraction
- Screen dimension recording
Records time spent on a page:
- Validates reasonable time ranges (0-7200 seconds)
- Links to existing visit records
- Updates custom data with time metrics
- Prevents data manipulation
Tracks custom events:
- Event name sanitization
- Visit association validation
- Custom data storage
- Event spam prevention (max 50 events per visit)
All API endpoints include rate limiting:
Route::post('/track-visit', [AnalyticsController::class, 'trackVisit'])
->middleware(['throttle:100,1']); // 100 requests per minute
Route::post('/track-time', [AnalyticsController::class, 'trackTime'])
->middleware(['throttle:50,1']); // 50 requests per minute
Route::post('/track-event', [AnalyticsController::class, 'trackEvent'])
->middleware(['throttle:200,1']); // 200 requests per minuteThe package includes translations for:
- English (
en/admin.php) - French (
fr/admin.php)
- Create a new language directory:
src/lang/{locale}/ - Copy
admin.phpfrom an existing language - Translate all string values
- The package will automatically load the translations
// Dashboard labels'analytics.period' => 'Period'
'analytics.total_visits' => 'Total visits'
'analytics.unique_visitors' => 'Unique visitors'
'analytics.bounce_rate' => 'Bounce rate'// Time periods
'analytics.7_days' => '7 days'
'analytics.30_days' => '30 days' 'analytics.all_time' => 'All time'// Chart labels
'analytics.visits_per_day' => 'Visits per day'
'analytics.browsers' => 'Browsers'
'analytics.platforms' => 'Platforms'
'analytics.devices' => 'Devices'The migration includes comprehensive indexing:
$table->index(['visited_at', 'url']);
$table->index(['visited_at', 'ip_hash']);
$table->index(['visited_at', 'is_bot']);
$table->index(['session_id', 'visited_at']);- Dashboard data cached for 15 minutes
- Automatic cache invalidation on new visits
- Separate cache keys for different periods/URLs
- Uses Laravel's configured cache driver
Consider implementing data retention policies:
// Example: Delete visits older than 2 years
Visit::where('visited_at', '<', now()->subYears(2))->delete();- IP address anonymization with daily salt rotation
- Referrer URL sanitization (removes query parameters)
- Custom data filtering and validation
- Consent-based tracking activation
- Right to be forgotten support (via IP hash deletion)
- CSRF protection on all endpoints
- Rate limiting to prevent abuse
- Input sanitization and validation
- SQL injection prevention via Eloquent ORM
- XSS protection in dashboard views
- No personally identifiable information stored
- Minimal data collection (only necessary analytics data)
- Automatic bot exclusion from statistics
- Session-based unique visitor detection
Contributions are welcome! Please:
- Fork the project
- Create a feature branch (
git checkout -b feature/analytics-feature) - Commit your changes (
git commit -m 'Add analytics feature') - Push to the branch (
git push origin feature/analytics-feature) - Open a Pull Request
# Clone the repository
git clone https://github.com/NetAuraTech/analytics-manager.git
# Install dependencies
composer install- Verify GDPR consent is properly implemented
- Check CSRF token availability
- Ensure API routes are accessible
- Verify JavaScript console for errors
- Check database migrations have run
- Verify visits table has data
- Clear application cache:
php artisan cache:clear - Check browser console for JavaScript errors
- Verify database indexes exist
- Check cache configuration
- Consider data retention policies
- Monitor database query performance
This package is open-source software licensed under the MIT license.
For support or questions:
- Email: contact@netauratech.fr
- Create an issue on GitHub
- Initial release
- Privacy-compliant visitor tracking
- Real-time analytics dashboard
- Bot detection and filtering
- GDPR compliance features
- Multi-language support
- Comprehensive API endpoints
- SPA tracking support
- Custom event tracking
- NetAuraTech - Initial work - NetAuraTech
© 2025 NetAuraTech. All rights reserved.