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

Laravel Analytics Laravel Package

spatie/laravel-analytics

Laravel package to retrieve Google Analytics data with a simple API. Fetch most visited pages, visitors and page views for a given period, returning Laravel Collections. Quick to install, configurable, and works nicely in dashboards and reports.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require spatie/laravel-analytics
    php artisan vendor:publish --tag="analytics-config"
    

    Configure .env with ANALYTICS_PROPERTY_ID and store the service account JSON file at storage_path('app/analytics/service-account-credentials.json').

  2. First Use Case: Fetch today’s most visited pages:

    use Spatie\Analytics\Facades\Analytics;
    use Spatie\Analytics\Period;
    
    $pages = Analytics::fetchMostVisitedPages(Period::today());
    
  3. Key Files:

    • config/analytics.php: Configuration (property ID, credentials, cache settings).
    • app/Providers/AppServiceProvider.php: Register facade (if not auto-discovered).

Implementation Patterns

Core Workflows

  1. Period-Based Queries: Use Period for time ranges (e.g., Period::days(7), Period::create($start, $end)). Example:

    $visitors = Analytics::fetchVisitorsAndPageViews(Period::weeks(4));
    
  2. Custom Reports: Leverage the get() method for advanced queries:

    $metrics = ['activeUsers', 'screenPageViews'];
    $dimensions = ['country', 'deviceCategory'];
    $results = Analytics::get(Period::months(3), $metrics, $dimensions);
    
  3. Caching: Default cache lifetime is 24 hours (configurable in analytics.php). Disable with cache_lifetime_in_minutes: 0.

  4. Integration with Views: Pass data to Blade:

    return view('analytics.dashboard', [
        'topPages' => Analytics::fetchMostVisitedPages(Period::today()),
    ]);
    
  5. Scheduled Reports: Use Laravel’s scheduler to fetch data periodically:

    // app/Console/Kernel.php
    $schedule->call(function () {
        $data = Analytics::fetchTotalVisitorsAndPageViews(Period::days(30));
        // Store in DB or send email
    })->daily();
    

Common Patterns

  • Filtering: Use FilterExpression for complex queries (e.g., event-based filters).
  • Pagination: Combine maxResults and offset for large datasets.
  • Error Handling: Wrap calls in try-catch for API rate limits or auth issues:
    try {
        $data = Analytics::fetchTopCountries(Period::today());
    } catch (\Exception $e) {
        Log::error("Analytics error: " . $e->getMessage());
    }
    

Gotchas and Tips

Pitfalls

  1. Credentials Security:

    • Never commit the service account JSON to Git. Use .gitignore:
      storage/app/analytics/service-account-credentials.json
      
    • Rotate credentials periodically via Google Cloud Console.
  2. Rate Limits:

    • Google Analytics API has quotas (e.g., 50,000 requests/day). Monitor usage in Google Cloud Console.
    • Implement exponential backoff for retries:
      use GuzzleHttp\Exception\RequestException;
      
      try {
          $data = Analytics::get(...);
      } catch (RequestException $e) {
          if ($e->getCode() === 429) {
              sleep(10); // Retry after delay
              retry();
          }
      }
      
  3. GA4 vs. Universal Analytics:

    • This package only supports GA4. Ensure your property ID is for GA4 (not UA).
  4. Cache Invalidation:

    • Clear cache manually if data is stale:
      php artisan cache:clear
      
    • Or disable caching temporarily for debugging.
  5. Time Zone Issues:

    • Google Analytics uses UTC. Convert dates explicitly:
      use Carbon\Carbon;
      $period = Period::create(
          Carbon::now()->timezone('UTC')->startOfDay(),
          Carbon::now()->timezone('UTC')->endOfDay()
      );
      

Debugging Tips

  1. Enable Logging: Add to analytics.php:

    'debug' => env('ANALYTICS_DEBUG', false),
    

    Logs API requests/responses to storage/logs/analytics.log.

  2. Validate Queries: Test queries in Google Analytics Data API Explorer first.

  3. Common Errors:

    • Invalid Credentials: Verify the service account email has "Analyst" access in GA4.
    • Property Not Found: Double-check ANALYTICS_PROPERTY_ID in .env.
    • Metric/Dimension Not Found: Use GA4 API reference to validate names.

Extension Points

  1. Custom Metrics/Dimensions: Extend the get() method for proprietary metrics:

    $customMetric = Analytics::get(
        Period::today(),
        ['customMetricName'], // Replace with your custom metric
        ['customDimensionName']
    );
    
  2. Database Storage: Cache results in a table (e.g., analytics_reports):

    // After fetching data
    AnalyticsReport::updateOrCreate(
        ['period' => $period->toDateString()],
        ['data' => $data->toArray()]
    );
    
  3. Real-Time Dashboards: Use Laravel Echo/Pusher to broadcast updates:

    // In a scheduled job
    broadcast(new AnalyticsUpdate($data))->toOthers();
    
  4. Multi-Property Support: Dynamically switch properties via config:

    config(['analytics.property_id' => $dynamicPropertyId]);
    

Performance Tips

  • Batch Requests: Combine multiple queries into a single API call where possible.
  • Lazy Loading: Use cursor() on Collections for large datasets:
    $pages = Analytics::fetchMostVisitedPages(Period::today())->cursor();
    
  • Avoid Over-Fetching: Limit maxResults to reduce payload size.
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