PHPackages                             orimyth/laravel-analytics - 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. orimyth/laravel-analytics

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

orimyth/laravel-analytics
=========================

Self-hosted, GDPR-compliant server-side analytics for Laravel with multi-tenancy support

03PHP

Since Nov 10Pushed 6mo agoCompare

[ Source](https://github.com/orimyth/laravel-analytics)[ Packagist](https://packagist.org/packages/orimyth/laravel-analytics)[ RSS](/packages/orimyth-laravel-analytics/feed)WikiDiscussions main Synced 1mo ago

READMEChangelogDependenciesVersions (1)Used By (0)

Laravel Analytics
=================

[](#laravel-analytics)

[![Latest Version on Packagist](https://camo.githubusercontent.com/761724e5a844fde068f1088d16b84e26c16dc5645dab3e7823e7355d954cb97a/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f6f72696d7974682f6c61726176656c2d616e616c79746963732e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/orimyth/laravel-analytics)[![Total Downloads](https://camo.githubusercontent.com/25408182a5e7160d4cfda1d276fd7a640336ccc339d99118b235c776b2cbdbe9/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f6f72696d7974682f6c61726176656c2d616e616c79746963732e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/orimyth/laravel-analytics)

A self-hosted, GDPR-compliant server-side analytics package for Laravel with multi-tenancy support. Track page views, events, conversions, and performance metrics without relying on third-party services.

Features
--------

[](#features)

- **Server-side tracking** - No client-side JavaScript required
- **GDPR compliant** - IP anonymization, no cookies, full data control
- **Multi-tenancy support** - Built-in support for multi-tenant applications
- **Performance monitoring** - Track response times, memory usage, and query counts
- **Queue support** - Async processing with Redis/Horizon
- **Data aggregation** - Hourly, daily, weekly, and monthly summaries
- **RESTful API** - Headless API for custom dashboards
- **Automatic tracking** - Middleware for hands-free analytics
- **Privacy-focused** - No external dependencies or data sharing

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

[](#requirements)

- PHP 8.1 or higher
- Laravel 10.x or 11.x
- MySQL 5.7+ or 8.0+
- Redis (optional, recommended for queue processing)

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

[](#installation)

Install the package via Composer:

```
composer require orimyth/laravel-analytics
```

Publish the configuration file:

```
php artisan vendor:publish --tag=insight-config
```

Run the migrations:

```
php artisan migrate
```

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

[](#configuration)

The configuration file is published to `config/insight.php`. Key options include:

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

    // Automatic request tracking
    'auto_track_requests' => env('INSIGHT_AUTO_TRACK_REQUESTS', true),

    // Performance tracking
    'auto_track_performance' => env('INSIGHT_AUTO_TRACK_PERFORMANCE', false),

    // Queue configuration
    'queue_connection' => env('INSIGHT_QUEUE_CONNECTION', 'redis'),
    'queue_name' => env('INSIGHT_QUEUE_NAME', 'insight'),

    // GDPR compliance
    'anonymize_ip' => env('INSIGHT_ANONYMIZE_IP', true),
    'track_user' => env('INSIGHT_TRACK_USER', true),
    'track_anonymous' => env('INSIGHT_TRACK_ANONYMOUS', true),

    // Multi-tenancy
    'multi_tenancy' => [
        'enabled' => env('INSIGHT_MULTI_TENANCY', false),
        'tenant_resolver' => function () {
            return tenant('id'); // Compatible with stancl/tenancy
        },
    ],

    // Data retention
    'retention_days' => env('INSIGHT_RETENTION_DAYS', 90),

    // Exclude routes, IPs, and user agents
    'excluded_routes' => ['horizon*', 'telescope*'],
    'excluded_ips' => [],
    'excluded_user_agents' => ['*bot*', '*crawler*'],
];
```

Usage
-----

[](#usage)

### Automatic Tracking

[](#automatic-tracking)

By default, Laravel Analytics automatically tracks all web requests. No additional code is required.

### Manual Tracking

[](#manual-tracking)

Track custom events using the `Insight` facade:

```
use Orimyth\LaravelAnalytics\Facades\Analytics;

// Track a page view
Analytics::pageView('/custom-page', ['metadata' => 'value']);

// Track a conversion
Analytics::conversion('signup', 100, ['plan' => 'premium']);

// Track a click
Analytics::click('cta-button', ['campaign' => 'summer-sale']);

// Track an API request
Analytics::apiRequest('/api/users');

// Track a custom event
Analytics::track('video_play', [
    'video_id' => 123,
    'duration' => 45,
]);
```

### Middleware

[](#middleware)

You can manually apply middleware to specific routes:

```
// Track page views only
Route::get('/dashboard', [DashboardController::class, 'index'])
    ->middleware('insight.pageview');

// Track performance metrics
Route::get('/reports', [ReportController::class, 'index'])
    ->middleware('insight.performance');

// Track both
Route::middleware(['insight.pageview', 'insight.performance'])
    ->group(function () {
        Route::get('/analytics', [AnalyticsController::class, 'index']);
    });
```

API Endpoints
-------------

[](#api-endpoints)

Laravel Analytics provides a RESTful API for querying analytics data:

### Events

[](#events)

```
GET /api/insight/events
```

Query parameters:

- `start_date` - Filter by start date (YYYY-MM-DD)
- `end_date` - Filter by end date (YYYY-MM-DD)
- `event_type` - Filter by event type (page\_view, click, conversion, etc.)
- `tenant_id` - Filter by tenant ID
- `user_id` - Filter by user ID
- `path` - Filter by path (supports wildcards)
- `per_page` - Results per page (max 100)
- `sort_by` - Sort field (default: created\_at)
- `sort_order` - Sort order (asc/desc)

### Summary Statistics

[](#summary-statistics)

```
GET /api/insight/summary?start_date=2024-01-01&end_date=2024-01-31
```

Returns:

```
{
  "total_events": 1234,
  "unique_sessions": 456,
  "unique_users": 123,
  "page_views": 890,
  "conversions": 45,
  "clicks": 234,
  "api_requests": 567,
  "performance": {
    "avg_response_time_ms": 123.45,
    "max_response_time_ms": 567.89,
    "avg_memory_mb": 45.67,
    "avg_query_count": 12.34
  }
}
```

### Performance Metrics

[](#performance-metrics)

```
GET /api/insight/metrics
```

Same query parameters as events endpoint.

### Trends

[](#trends)

```
GET /api/insight/trends?dimension=event_type&aggregate_type=daily
```

Query parameters:

- `dimension` - Dimension to group by (event\_type, path, browser, platform, device\_type)
- `aggregate_type` - Aggregation level (hourly, daily, weekly, monthly)
- `start_date` - Start date
- `end_date` - End date
- `tenant_id` - Filter by tenant

### Top Pages

[](#top-pages)

```
GET /api/insight/top-pages?limit=10
```

### Top Referrers

[](#top-referrers)

```
GET /api/insight/top-referrers?limit=10
```

### Browser/Platform/Device Statistics

[](#browserplatformdevice-statistics)

```
GET /api/insight/browsers
GET /api/insight/platforms
GET /api/insight/devices
```

Artisan Commands
----------------

[](#artisan-commands)

### Aggregate Data

[](#aggregate-data)

Aggregate raw events into summary statistics:

```
# Daily aggregation (default)
php artisan insight:aggregate

# Hourly aggregation
php artisan insight:aggregate --type=hourly

# Specific date
php artisan insight:aggregate --date=2024-01-15

# Specific tenant
php artisan insight:aggregate --tenant=tenant-123
```

Schedule aggregations in `app/Console/Kernel.php`:

```
$schedule->command('insight:aggregate --type=hourly')->hourly();
$schedule->command('insight:aggregate --type=daily')->daily();
```

### Clean Up Old Data

[](#clean-up-old-data)

Remove old analytics data based on retention policy:

```
# Clean up based on config retention_days
php artisan insight:cleanup

# Custom retention period
php artisan insight:cleanup --days=30

# Preview without deleting
php artisan insight:cleanup --dry-run
```

Schedule cleanup:

```
$schedule->command('insight:cleanup')->weekly();
```

### Optimize Database

[](#optimize-database)

Optimize database tables for better performance:

```
php artisan insight:optimize
```

Multi-Tenancy Support
---------------------

[](#multi-tenancy-support)

Laravel Analytics is compatible with [stancl/tenancy](https://github.com/archtechx/tenancy):

```
// config/insight.php
'multi_tenancy' => [
    'enabled' => true,
    'tenant_resolver' => function () {
        return tenant('id');
    },
],
```

All events and metrics will automatically include the tenant context.

Queue Configuration
-------------------

[](#queue-configuration)

For optimal performance, configure Redis as your queue connection:

```
INSIGHT_QUEUE_CONNECTION=redis
INSIGHT_QUEUE_NAME=insight
```

Process the queue with Laravel Horizon or a queue worker:

```
php artisan queue:work redis --queue=insight
```

Privacy &amp; GDPR Compliance
-----------------------------

[](#privacy--gdpr-compliance)

Laravel Analytics is designed with privacy in mind:

- **IP Anonymization**: Last octet of IPv4 and last 80 bits of IPv6 are removed by default
- **No Cookies**: Server-side tracking doesn't require cookies
- **Data Ownership**: All data is stored in your own database
- **User Control**: Users can be excluded from tracking
- **Data Retention**: Automatic cleanup of old data

To exclude specific users from tracking:

```
// In a middleware or service provider
if (auth()->user()?->opted_out_of_analytics) {
    config(['insight.enabled' => false]);
}
```

Performance Considerations
--------------------------

[](#performance-considerations)

- Enable queue processing for production environments
- Run aggregations regularly to improve query performance
- Use the aggregates table for dashboard queries
- Consider partitioning tables for large datasets
- Run `insight:optimize` periodically

Testing
-------

[](#testing)

```
composer test
```

Security
--------

[](#security)

If you discover any security-related issues, please email  instead of using the issue tracker.

Credits
-------

[](#credits)

- [Orimyth](https://github.com/orimyth)
- [All Contributors](../../contributors)

License
-------

[](#license)

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

Roadmap
-------

[](#roadmap)

Future features under consideration:

- Real-time tracking via WebSocket
- AI-based anomaly detection
- Custom dashboard UI (Filament/Livewire)
- Export functionality (CSV, JSON)
- Integration with Laravel Pulse
- Geographic visualization
- A/B testing support
- Funnel analysis
- User journey tracking

Support
-------

[](#support)

For support, please open an issue on [GitHub](https://github.com/orimyth/laravel-analytics/issues).

###  Health Score

17

—

LowBetter than 6% of packages

Maintenance47

Moderate activity, may be stable

Popularity3

Limited adoption so far

Community2

Small or concentrated contributor base

Maturity13

Early-stage or recently created project

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.

### Community

Maintainers

![](https://www.gravatar.com/avatar/7063d2ceed3dd3bb73b9a325d85a462add46941c02c91e2c9e66363352961251?d=identicon)[shayannos](/maintainers/shayannos)

### Embed Badge

![Health badge](/badges/orimyth-laravel-analytics/health.svg)

```
[![Health](https://phpackages.com/badges/orimyth-laravel-analytics/health.svg)](https://phpackages.com/packages/orimyth-laravel-analytics)
```

PHPackages © 2026

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