Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Analytics Statistics Laravel Package

spatie/analytics-statistics

Opinionated PHP package to fetch Google Analytics statistics. Provides a simple API for querying Analytics data using Google credentials. Works with PHP 5.3+; Laravel 5 users may prefer spatie/laravel-analytics.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require spatie/analytics-statistics
    

    For Laravel 5, use spatie/laravel-analytics instead (this package is legacy).

  2. Configuration: Add your Google Analytics credentials to .env:

    GOOGLE_ANALYTICS_VIEW_ID=your_view_id
    GOOGLE_ANALYTICS_PROFILE_ID=your_profile_id
    GOOGLE_ANALYTICS_CLIENT_ID=your_client_id
    GOOGLE_ANALYTICS_CLIENT_SECRET=your_client_secret
    GOOGLE_ANALYTICS_REFRESH_TOKEN=your_refresh_token
    
  3. Publish Config (if needed):

    php artisan vendor:publish --provider="Spatie\AnalyticsStatistics\AnalyticsStatisticsServiceProvider"
    

    Configure in config/analytics-statistics.php.

  4. First Query:

    use Spatie\AnalyticsStatistics\Facades\AnalyticsStatistics;
    
    $stats = AnalyticsStatistics::get('ga:sessions', [
        'dimensions' => 'ga:date',
        'metrics' => 'ga:sessions,ga:users',
        'start-date' => '30daysAgo',
        'end-date' => 'today',
    ]);
    

Implementation Patterns

Core Workflows

  1. Fetching Data: Use the fluent facade for common queries:

    // Get daily sessions for the last 7 days
    $stats = AnalyticsStatistics::get('ga:sessions', [
        'dimensions' => 'ga:date',
        'metrics' => 'ga:sessions',
        'start-date' => '7daysAgo',
        'end-date' => 'today',
        'sort' => '-ga:date',
    ]);
    
  2. Processing Results: Loop through rows and format data:

    foreach ($stats->rows() as $row) {
        $date = $row['ga:date'];
        $sessions = $row['ga:sessions'];
        // Store in DB or process further
    }
    
  3. Caching Responses: Cache frequent queries to reduce API calls:

    $stats = AnalyticsStatistics::remember('daily_sessions', now()->addHours(1), function () {
        return AnalyticsStatistics::get('ga:sessions', [...]);
    });
    
  4. Integration with Laravel: Bind the service to the container in AppServiceProvider:

    $this->app->singleton(AnalyticsStatistics::class, function () {
        return new AnalyticsStatistics(config('analytics-statistics'));
    });
    
  5. Scheduled Reports: Use Laravel's scheduler to run analytics jobs:

    // app/Console/Kernel.php
    protected function schedule(Schedule $schedule)
    {
        $schedule->call(function () {
            $stats = AnalyticsStatistics::get('ga:pageviews', [...]);
            // Process and store data
        })->daily();
    }
    

Advanced Patterns

  1. Custom Metrics/Dimensions: Extend the package by creating a custom query builder:

    class CustomAnalytics extends AnalyticsStatistics
    {
        public function customQuery()
        {
            return $this->get('ga:customMetric', [
                'dimensions' => 'ga:customDimension1',
                'metrics' => 'ga:customMetric1,ga:customMetric2',
            ]);
        }
    }
    
  2. Data Transformation: Use Laravel's collection methods to transform raw data:

    $transformed = $stats->rows()->map(function ($row) {
        return [
            'date' => $row['ga:date'],
            'sessions' => (int) $row['ga:sessions'],
            'users' => (int) $row['ga:users'],
        ];
    });
    
  3. Multi-View Queries: Query multiple views in a single request:

    $stats = AnalyticsStatistics::get('ga:sessions', [
        'dimensions' => 'ga:date',
        'metrics' => 'ga:sessions',
        'start-date' => '7daysAgo',
        'end-date' => 'today',
        'filters' => 'ga:viewId==123456;ga:viewId==654321', // Comma-separated view IDs
    ]);
    
  4. Error Handling: Wrap queries in try-catch blocks:

    try {
        $stats = AnalyticsStatistics::get('ga:pageviews', [...]);
    } catch (\Exception $e) {
        Log::error("Analytics error: " . $e->getMessage());
        // Fallback logic
    }
    

Gotchas and Tips

Common Pitfalls

  1. Deprecated Package:

  2. Authentication Issues:

    • Ensure GOOGLE_ANALYTICS_REFRESH_TOKEN is valid and has the correct scopes (https://www.googleapis.com/auth/analytics.readonly).
    • If using OAuth2, regenerate tokens if they expire.
  3. Rate Limits:

    • Google Analytics API has quota limits. Cache responses aggressively:
      $stats = AnalyticsStatistics::remember('monthly_report', now()->addDays(30), function () {
          return AnalyticsStatistics::get('ga:sessions', [...]);
      });
      
  4. Date Ranges:

    • Invalid date ranges (e.g., start-date after end-date) will return empty results. Validate inputs:
      $start = '30daysAgo';
      $end = 'today';
      if (strtotime($start) > strtotime($end)) {
          throw new \InvalidArgumentException("Invalid date range");
      }
      
  5. Legacy PHP Support:

    • Requires PHP ≥ 5.3. If using PHP 7+, consider upgrading to a modern package.

Debugging Tips

  1. Enable Debugging: Set debug to true in config/analytics-statistics.php to log raw API responses:

    'debug' => env('APP_DEBUG', false),
    
  2. Check API Responses: Inspect the $stats->raw() property to debug malformed responses:

    dd($stats->raw());
    
  3. Validate Metrics/Dimensions: Use Google's Core Reporting API Dimension/Metric Explorer to verify valid metrics/dimensions.

  4. Token Expiry: If you get 401 Unauthorized, regenerate your OAuth2 tokens and update .env.


Extension Points

  1. Custom Query Builder: Extend the base class to add domain-specific methods:

    class AppAnalytics extends AnalyticsStatistics
    {
        public function userRetention()
        {
            return $this->get('ga:users', [
                'dimensions' => 'ga:date',
                'metrics' => 'ga:users',
                'cohortNthDay' => 7, // 7-day retention
                'cohortNthMonth' => 1,
            ]);
        }
    }
    
  2. Event-Based Analytics: Trigger analytics queries on events (e.g., released:post-published):

    // In an event listener
    AnalyticsStatistics::dispatch(function () {
        $stats = AnalyticsStatistics::get('ga:pageviews', [
            'filters' => 'ga:pagePath=~/blog/.*',
        ]);
        // Process data
    });
    
  3. Database Storage: Store raw or processed analytics data in a local database for faster access:

    $stats->rows()->each(function ($row) {
        AnalyticsData::updateOrCreate(
            ['date' => $row['ga:date']],
            ['sessions' => $row['ga:sessions']]
        );
    });
    
  4. Webhook Integration: Use Laravel's queues to process analytics data asynchronously:

    AnalyticsStatistics::dispatch(function () {
        $stats = AnalyticsStatistics::get('ga:sessions', [...]);
        // Process and store data
    })->onQueue('analytics');
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
davejamesmiller/laravel-breadcrumbs
artisanry/parsedown
christhompsontldr/phpsdk
enqueue/dsn
bunny/bunny
enqueue/test
enqueue/null
enqueue/amqp-tools
milesj/emojibase
bower-asset/punycode
bower-asset/inputmask
bower-asset/jquery
bower-asset/yii2-pjax
laravel/nova
spatie/laravel-mailcoach
spatie/laravel-superseeder
laravel/liferaft
nst/json-test-suite
danielmiessler/sec-lists
jackalope/jackalope-transport