PHPackages                             zfhassaan/genlytics - 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. zfhassaan/genlytics

ActiveLibrary

zfhassaan/genlytics
===================

Genlytics is a powerful Google Analytics Composer package that allows for easy data collection, analysis, and visualization. Optimized for SEO, it helps improve website performance and drive more organic traffic.

v1.0.4(5mo ago)51142MITPHPPHP ^8.1CI passing

Since May 3Pushed 4mo agoCompare

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

READMEChangelog (6)Dependencies (13)Versions (7)Used By (0)

 [![](banner.jpeg)](banner.jpeg)

[![Latest Version on Packagist](https://camo.githubusercontent.com/f2b53bcfc6992c22c84a9d995ed40e9e54639a203bcb3a278e7ae3a46417875a/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f7a666861737361616e2f67656e6c79746963732e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/zfhassaan/genlytics)[![MIT Licensed](https://camo.githubusercontent.com/55c0218c8f8009f06ad4ddae837ddd05301481fcf0dff8e0ed9dadda8780713e/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6c6963656e73652d4d49542d627269676874677265656e2e7376673f7374796c653d666c61742d737175617265)](LICENSE)[![Tests](https://github.com/zfhassaan/genlytics/actions/workflows/tests.yml/badge.svg?branch=main)](https://github.com/zfhassaan/genlytics/actions/workflows/tests.yml)[![Total Downloads](https://camo.githubusercontent.com/824157ca420b2f4f5d7c00ec997d9a89de5809a9ce9b1283bd79a196e0a2b768/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f7a666861737361616e2f67656e6c79746963732e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/zfhassaan/genlytics)[![Laravel 10–12](https://camo.githubusercontent.com/c45f9843cdb48719a12ab2b4554c03cfb19a6adcc9a70cbdd2707fa47b906da1/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f4c61726176656c2d31302e7825323025374325323031312e7825323025374325323031322e782d4646324432303f7374796c653d666c61742d737175617265266c6f676f3d6c61726176656c266c6f676f436f6c6f723d7768697465)](https://camo.githubusercontent.com/c45f9843cdb48719a12ab2b4554c03cfb19a6adcc9a70cbdd2707fa47b906da1/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f4c61726176656c2d31302e7825323025374325323031312e7825323025374325323031322e782d4646324432303f7374796c653d666c61742d737175617265266c6f676f3d6c61726176656c266c6f676f436f6c6f723d7768697465)[![Hits](https://camo.githubusercontent.com/65a48c0506ef3309636fc99f7d6a7589c8b1274061c3cd70d34d80a5b5d44bb9/68747470733a2f2f686974732e736565796f756661726d2e636f6d2f6170692f636f756e742f696e63722f62616467652e7376673f75726c3d68747470732533412532462532466769746875622e636f6d2532467a666861737361616e25324667656e6c797469637326636f756e745f62673d253233373943383344267469746c655f62673d2532333535353535352669636f6e3d2669636f6e5f636f6c6f723d253233453745374537267469746c653d6869747326656467655f666c61743d66616c7365)](https://hits.seeyoufarm.com)

### Disclaimer

[](#disclaimer)

The Google UA Property is going away from July 2023. Google is implementing the Google Analytics V4. *Universal Analytics will no longer process new data in standard properties beginning on 1 July 2023. Prepare now by setting up and switching over to a Google Analytics 4 property.*[Learn More](https://support.google.com/analytics/answer/11583528?hl=en-GB&authuser=0)

The Google Analytics data will only be available through the GCP API.

About
-----

[](#about)

Genlytics is a powerful Google Analytics 4 (GA4) package for Laravel, completely rewritten with **Repository pattern**, **Event-driven architecture**, and **performance optimizations**. The package integrates seamlessly with your Laravel application, providing intelligent caching, background job processing, and real-time analytics updates.

### Key Features

[](#key-features)

- **Repository Pattern** - Abstracted data access layer for easy testing and extension
- **Event-Driven** - Decoupled event system for extensibility
- **Intelligent Caching** - Automatic cache management with configurable TTL (90%+ API call reduction)
- **Background Jobs** - Non-blocking analytics queries for better performance
- **Real-Time Updates** - Automatic refresh scheduling for live dashboards
- **Type Safety** - Full type hints and comprehensive PHPDoc
- **Error Handling** - Robust error handling with logging
- **Comprehensive Tests** - 52 test cases with 83+ assertions
- **Backward Compatible** - Existing code works without changes

### Architecture Highlights

[](#architecture-highlights)

- **Single Responsibility** - Each class has one clear purpose
- **Dependency Inversion** - Dependencies on abstractions, not concretions
- **Interface Segregation** - Focused, specific interfaces
- **Open/Closed** - Extensible via interfaces without modification

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

[](#requirements)

- PHP 8.1 or higher
- Laravel 9.0 or higher
- Google Analytics 4 (GA4) property
- Google Cloud Platform project with Analytics Data API enabled
- Service account with Analytics access

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

[](#installation)

Install the package via Composer:

```
composer require zfhassaan/genlytics
```

### Auto-Discovery

[](#auto-discovery)

The package supports Laravel's auto-discovery, so the service provider and facade will be automatically registered. No manual configuration needed!

### Manual Registration (Optional)

[](#manual-registration-optional)

If you prefer manual registration, add to `config/app.php`:

```
'providers' => [
    // ...
    zfhassaan\genlytics\provider\AnalyticsServiceProvider::class,
],

'aliases' => [
    // ...
    'Genlytics' => zfhassaan\genlytics\facades\AnalyticsFacade::class,
],
```

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

[](#configuration)

### Publish Configuration

[](#publish-configuration)

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

Or publish everything:

```
php artisan vendor:publish --provider="zfhassaan\genlytics\provider\AnalyticsServiceProvider"
```

### Environment Variables

[](#environment-variables)

Add to your `.env` file:

```
# Required
GENLYTICS_PROPERTY_ID=your-property-id-here
GENLYTICS_CREDENTIALS=storage/app/analytics/service-account.json

# Optional - Cache Configuration
GENLYTICS_ENABLE_CACHE=true
GENLYTICS_CACHE_LIFETIME=1440

# Optional - Background Jobs
GENLYTICS_USE_BACKGROUND_JOBS=true
GENLYTICS_QUEUE_CONNECTION=redis
GENLYTICS_QUEUE_NAME=default

# Optional - Real-Time Updates
GENLYTICS_ENABLE_REALTIME_UPDATES=true
GENLYTICS_REALTIME_CACHE_LIFETIME=30
```

### Google Analytics Setup

[](#google-analytics-setup)

1. **Create GA4 Property** - Create a Google Analytics 4 property
2. **Enable Analytics Data API** - Enable in Google Cloud Console
3. **Create Service Account** - Create service account in GCP
4. **Generate JSON Key** - Download service account JSON key
5. **Grant Analytics Access** - Add service account email to GA4 property with Viewer/Analyst role

See [Installation Guide](wiki/Installation-Guide.md) for detailed steps.

Usage
-----

[](#usage)

### Basic Usage

[](#basic-usage)

```
use zfhassaan\genlytics\Genlytics;

$analytics = new Genlytics();
```

Or use the facade:

```
use Genlytics;

$result = Genlytics::runReports(...);
```

Or dependency injection:

```
use zfhassaan\genlytics\Genlytics;

class AnalyticsController extends Controller
{
    public function __construct(
        protected Genlytics $analytics
    ) {}
}
```

### Running Reports

[](#running-reports)

#### Basic Report

[](#basic-report)

```
$period = [
    'start_date' => '7daysAgo',
    'end_date' => 'today'
];

$dimensions = [['name' => 'country']];
$metrics = [['name' => 'activeUsers']];

$result = $analytics->runReports($period, $dimensions, $metrics);
```

#### Multiple Dimensions and Metrics

[](#multiple-dimensions-and-metrics)

```
$dimensions = [
    ['name' => 'country'],
    ['name' => 'city'],
    ['name' => 'deviceCategory'],
];

$metrics = [
    ['name' => 'activeUsers'],
    ['name' => 'sessions'],
    ['name' => 'bounceRate'],
];

$result = $analytics->runReports($period, $dimensions, $metrics);
```

#### With Options

[](#with-options)

```
$options = [
    'limit' => 100,
    'offset' => 0,
    'orderBys' => [
        [
            'metric' => [
                'metricName' => 'activeUsers'
            ],
            'desc' => true
        ]
    ]
];

$result = $analytics->runReports($period, $dimensions, $metrics, $options);
```

#### Force Refresh (Bypass Cache)

[](#force-refresh-bypass-cache)

```
$result = $analytics->runReports(
    $period,
    $dimensions,
    $metrics,
    [],
    true // Force refresh from API
);
```

### Real-Time Reports

[](#real-time-reports)

```
$dimensions = [['name' => 'country']];
$metrics = [['name' => 'activeUsers']];

$result = $analytics->runRealTime($dimensions, $metrics);
```

### Dimension Reports

[](#dimension-reports)

```
$period = [
    'start_date' => '30daysAgo',
    'end_date' => 'today'
];

// Single dimension
$result = $analytics->runDimensionReport($period, 'country');

// Multiple dimensions
$result = $analytics->runDimensionReport($period, ['country', 'city']);
```

### Response Format

[](#response-format)

```
{
    "data": [
        {
            "dimensions": {
                "country": "United States",
                "city": "New York"
            },
            "metrics": {
                "activeUsers": "1250",
                "sessions": "1500"
            }
        }
    ],
    "metadata": {
        "count": 1,
        "timestamp": "2024-01-01T00:00:00Z"
    }
}
```

Advanced Features
-----------------

[](#advanced-features)

### Caching

[](#caching)

Genlytics automatically caches analytics data to reduce API calls:

```
// Cache is enabled by default
// Configure in config/analytics.php or .env
GENLYTICS_ENABLE_CACHE=true
GENLYTICS_CACHE_LIFETIME=1440  // 24 hours in minutes
```

**Benefits:**

- 90%+ reduction in API calls
- Faster response times
- Lower API quota usage

### Background Jobs

[](#background-jobs)

Process analytics queries in the background:

```
// Enable in config
GENLYTICS_USE_BACKGROUND_JOBS=true

// Requires queue worker
php artisan queue:work
```

**Benefits:**

- Non-blocking requests
- Better user experience
- Automatic cache refresh

### Real-Time Updates

[](#real-time-updates)

Automatic real-time data refresh:

```
// Enable in config
GENLYTICS_ENABLE_REALTIME_UPDATES=true
GENLYTICS_REALTIME_CACHE_LIFETIME=30  // seconds
```

### Events

[](#events)

Listen to analytics events:

```
use zfhassaan\genlytics\Events\AnalyticsDataFetched;
use Illuminate\Support\Facades\Event;

Event::listen(AnalyticsDataFetched::class, function ($event) {
    Log::info('Analytics data fetched', [
        'type' => $event->reportType,
        'from_cache' => $event->fromCache,
        'data_count' => count($event->data),
    ]);
});
```

**Available Events:**

- `AnalyticsDataRequested` - Fired when data is requested
- `AnalyticsDataFetched` - Fired when data is successfully fetched
- `AnalyticsCacheUpdated` - Fired when cache is updated
- `AnalyticsQueryFailed` - Fired when query fails

### Using Repository Directly

[](#using-repository-directly)

For advanced usage, access the repository:

```
use zfhassaan\genlytics\Contracts\AnalyticsRepositoryInterface;

$repository = app(AnalyticsRepositoryInterface::class);

$response = $repository->runReport(
    $dateRange,
    $dimensions,
    $metrics,
    $options
);
```

Publishing Test Cases
---------------------

[](#publishing-test-cases)

Publish test cases to your application for customization:

```
php artisan vendor:publish --tag=genlytics-tests
```

This publishes:

- `tests/Genlytics/TestCase.php` - Base test case
- `tests/Genlytics/Unit/` - Unit tests
- `tests/Genlytics/Feature/` - Feature tests
- `tests/Genlytics/Integration/` - Integration tests

See [PUBLISHING.md](tests/PUBLISHING.md) for details.

Testing
-------

[](#testing)

Run the test suite:

```
composer test
```

Or with coverage:

```
composer test-coverage
```

**Test Coverage:**

- 52 test cases
- 83+ assertions
- All major components tested
- Mocks for external dependencies (no real API calls needed)

Cache Management
----------------

[](#cache-management)

### Clear Cache

[](#clear-cache)

```
php artisan genlytics:refresh-cache --clear
```

### Refresh Specific Cache

[](#refresh-specific-cache)

```
php artisan genlytics:refresh-cache --type=report
php artisan genlytics:refresh-cache --type=realtime
```

### Programmatic Cache Management

[](#programmatic-cache-management)

```
use zfhassaan\genlytics\Contracts\CacheManagerInterface;

$cacheManager = app(CacheManagerInterface::class);

// Clear specific cache
$cacheManager->forget('report:abc123');

// Clear all cache
$cacheManager->clear();
```

Common Use Cases
----------------

[](#common-use-cases)

### Dashboard Widget

[](#dashboard-widget)

```
class DashboardController extends Controller
{
    public function analytics(Genlytics $analytics)
    {
        $period = [
            'start_date' => '30daysAgo',
            'end_date' => 'today'
        ];

        $metrics = [['name' => 'activeUsers']];

        $users = $analytics->runReports($period, [], $metrics);

        return view('dashboard.analytics', [
            'users' => $users->getData(true)
        ]);
    }
}
```

### Real-Time Visitor Count

[](#real-time-visitor-count)

```
public function liveVisitors(Genlytics $analytics)
{
    $metrics = [['name' => 'activeUsers']];
    $result = $analytics->runRealTime([], $metrics);

    return response()->json([
        'visitors' => $result->getData(true)['data'][0]['metrics']['activeUsers'] ?? 0
    ]);
}
```

### Top Countries Report

[](#top-countries-report)

```
public function topCountries(Genlytics $analytics)
{
    $period = ['start_date' => '30daysAgo', 'end_date' => 'today'];
    $dimensions = [['name' => 'country']];
    $metrics = [['name' => 'activeUsers']];

    $options = [
        'orderBys' => [
            [
                'metric' => ['metricName' => 'activeUsers'],
                'desc' => true
            ]
        ],
        'limit' => 10
    ];

    return $analytics->runReports($period, $dimensions, $metrics, $options);
}
```

Error Handling
--------------

[](#error-handling)

```
try {
    $result = $analytics->runReports($period, $dimensions, $metrics);
} catch (\Exception $e) {
    Log::error('Analytics error', [
        'error' => $e->getMessage(),
    ]);

    return response()->json([
        'error' => 'Failed to fetch analytics data'
    ], 500);
}
```

Performance Optimizations
-------------------------

[](#performance-optimizations)

1. **Intelligent Caching** - Reduces API calls by 90%+
2. **Background Processing** - Non-blocking requests
3. **Query Optimization** - Efficient parameter handling
4. **Real-Time Scheduling** - Automatic refresh management

Documentation
-------------

[](#documentation)

- [Installation Guide](wiki/Installation-Guide.md) - Step-by-step setup
- [Configuration Guide](wiki/Configuration-Guide.md) - All configuration options
- [Usage Guide](wiki/Usage-Guide.md) - Usage examples and best practices
- [Troubleshooting](wiki/Troubleshooting.md) - Common issues and solutions
- [How to Release](wiki/How-to-Release.md) - Release process
- [Contributing](wiki/Contributing.md) - Contribution guidelines
- [Architecture](ARCHITECTURE.md) - Architecture documentation
- [Migration Guide](MIGRATION.md) - Migration from v1.x to v2.0

Changelog
---------

[](#changelog)

See [CHANGELOG.md](CHANGELOG.md) for all changes.

### v2.0.0 - Major Rewrite

[](#v200---major-rewrite)

- Complete rewrite with modern architecture
- Repository pattern implementation
- Event-driven architecture
- Intelligent caching system
- Background job processing
- Real-time updates
- Comprehensive test suite
- Enhanced error handling
- Full backward compatibility

Support
-------

[](#support)

- [GitHub Issues](https://github.com/zfhassaan/genlytics/issues)
- [GitHub Wiki](https://github.com/zfhassaan/genlytics.wiki)

License
-------

[](#license)

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

Author
------

[](#author)

- **Author**: Hassaan Ali
- **Email**:

---

**Made with ❤️ for the Laravel community**

###  Health Score

42

—

FairBetter than 90% of packages

Maintenance73

Regular maintenance activity

Popularity16

Limited adoption so far

Community10

Small or concentrated contributor base

Maturity57

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 89.9% 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

Every ~236 days

Total

5

Last Release

157d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/3f91e22a64582fa1db957f7f189736d6cd2e6f1f69c2236a42a9ee8fcbdd0723?d=identicon)[zfhassaan](/maintainers/zfhassaan)

---

Top Contributors

[![zfhassaan](https://avatars.githubusercontent.com/u/17079656?v=4)](https://github.com/zfhassaan "zfhassaan (62 commits)")[![salman-mahmood](https://avatars.githubusercontent.com/u/28801084?v=4)](https://github.com/salman-mahmood "salman-mahmood (7 commits)")

---

Tags

analyticsgenlyticsgooglelaravellaravel-frameworklaravel-packagepackagephptracking

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/zfhassaan-genlytics/health.svg)

```
[![Health](https://phpackages.com/badges/zfhassaan-genlytics/health.svg)](https://phpackages.com/packages/zfhassaan-genlytics)
```

###  Alternatives

[google/gax

Google API Core for PHP

263103.1M454](/packages/google-gax)[googleads/google-ads-php

Google Ads API client for PHP

3497.6M9](/packages/googleads-google-ads-php)[google/cloud

Google Cloud Client Library

1.2k16.2M53](/packages/google-cloud)[google/grpc-gcp

gRPC GCP library for channel management

18497.8M3](/packages/google-grpc-gcp)[temporal/sdk

Temporal SDK

4002.2M18](/packages/temporal-sdk)[google/cloud-core

Google Cloud PHP shared dependency, providing functionality useful to all components.

343121.4M79](/packages/google-cloud-core)

PHPackages © 2026

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