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 in your app. Provides simple methods to fetch visitors, page views, and most visited pages over a given period, returning results as Laravel Collections via an easy-to-use facade.

View on GitHub
Deep Wiki
Context7
## Getting Started

### Minimal Setup
1. **Install the package**:
   ```bash
   composer require spatie/laravel-analytics
  1. Publish the config (optional but recommended):
    php artisan vendor:publish --tag="analytics-config"
    
  2. Configure credentials:
    • Set ANALYTICS_PROPERTY_ID in .env.
    • Place your service-account-credentials.json in storage/app/analytics/ (or update the config path).
  3. Grant permissions in Google Analytics Admin > Property Access Management (add the service account email with "Analyst" role).

First Use Case: Fetching Basic Metrics

use Spatie\Analytics\Facades\Analytics;
use Spatie\Analytics\Period;

// Fetch today's most visited pages
$pages = Analytics::fetchMostVisitedPages(Period::today());

// Fetch weekly visitors and pageviews
$data = Analytics::fetchVisitorsAndPageViews(Period::days(7));

Implementation Patterns

Common Workflows

  1. Dashboard Integration

    • Use fetchVisitorsAndPageViews(Period::days(7)) to populate a weekly traffic chart.
    • Cache results for 24 hours (default) to reduce API calls:
      $data = Analytics::fetchTotalVisitorsAndPageViews(Period::months(6));
      
  2. Custom Reports

    • Leverage the get() method for ad-hoc queries:
      $metrics = ['activeUsers', 'screenPageViews'];
      $dimensions = ['country', 'deviceCategory'];
      $results = Analytics::get(
          Period::days(30),
          $metrics,
          $dimensions,
          maxResults: 10
      );
      
  3. Event Tracking

    • Filter for specific events (e.g., form submissions):
      $dimensionFilter = new FilterExpression([
          'filter' => new Filter([
              'field_name' => 'eventName',
              'string_filter' => new StringFilter([
                  'match_type' => MatchType::EXACT,
                  'value' => 'form_submit',
              ]),
          ]),
      ]);
      $events = Analytics::get(
          Period::days(7),
          ['eventCount'],
          ['eventName'],
          dimensionFilter: $dimensionFilter
      );
      
  4. Pagination

    • Use offset and maxResults for large datasets:
      $firstPage = Analytics::get(Period::today(), ['pageViews'], [], maxResults: 50);
      $secondPage = Analytics::get(Period::today(), ['pageViews'], [], maxResults: 50, offset: 50);
      

Integration Tips

  • Laravel Cache: Use cache()->remember() to store results beyond the package’s default cache lifetime:
    $data = cache()->remember("analytics_{$period->startDate->format('Y-m-d')}", now()->addHours(1), function () use ($period) {
        return Analytics::fetchVisitorsAndPageViews($period);
    });
    
  • API Rate Limits: Monitor usage via Google Cloud Console to avoid hitting quotas.
  • Error Handling: Wrap calls in try-catch for Google\ApiCore\ApiException:
    try {
        $data = Analytics::fetchTopCountries(Period::days(7));
    } catch (ApiException $e) {
        Log::error("Analytics API error: " . $e->getMessage());
        return back()->with('error', 'Failed to fetch analytics data.');
    }
    

Gotchas and Tips

Pitfalls

  1. Credential Security

    • Never commit service-account-credentials.json to version control. Add it to .gitignore:
      storage/app/analytics/service-account-credentials.json
      
    • Rotate keys periodically via Google Cloud Console.
  2. GA4 Property ID

    • Ensure the ANALYTICS_PROPERTY_ID matches the GA4 property ID (not Universal Analytics). Format: properties/12345678.
  3. Cache Invalidation

    • The package caches responses by default (60 minutes). Clear manually if data appears stale:
      php artisan cache:clear
      
    • Disable caching in config/analytics.php for real-time data:
      'cache_lifetime_in_minutes' => 0,
      
  4. Dimension/Metric Limits

    • Google Analytics API enforces limits (e.g., max 10 dimensions/metrics per query). Use the get() method for complex queries.
  5. Time Zone Handling

    • Periods use the server’s time zone (configured in config/app.php). Convert to UTC if needed:
      use Carbon\Carbon;
      $period = Period::create(
          Carbon::now()->timezone('UTC')->startOfDay(),
          Carbon::now()->timezone('UTC')->endOfDay()
      );
      

Debugging Tips

  1. Enable API Logging Add to config/analytics.php:

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

    Logs will appear in storage/logs/laravel.log.

  2. Validate Queries Use the Google Analytics Data API Query Explorer to test queries before implementing them in Laravel.

  3. Common Errors

    • Invalid credentials: Verify the service account email has "Analyst" access in GA4.
    • Property not found: Double-check the ANALYTICS_PROPERTY_ID format.
    • Quota exceeded: Reduce query frequency or upgrade your Google Cloud plan.

Extension Points

  1. Custom Periods Extend the Period class for reusable time ranges:

    namespace App\Extensions;
    
    use Spatie\Analytics\Period;
    use Carbon\Carbon;
    
    class CustomPeriod extends Period
    {
        public static function lastBusinessWeek(): self
        {
            $start = Carbon::now()->startOfWeek()->subDays(Carbon::now()->dayOfWeek - 1);
            $end = Carbon::now()->endOfWeek();
            return new self($start, $end);
        }
    }
    
  2. Decorate the Facade Add helper methods to the Analytics facade:

    // app/Providers/AppServiceProvider.php
    use Spatie\Analytics\Facades\Analytics;
    
    public function boot()
    {
        Analytics::macro('topPagesByTraffic', function ($period, $limit = 5) {
            return $this->fetchMostVisitedPages($period)->sortByDesc('screenPageViews')->take($limit);
        });
    }
    

    Usage:

    $topPages = Analytics::topPagesByTraffic(Period::days(30));
    
  3. Event Listeners Trigger actions on analytics data changes (e.g., send Slack alerts for traffic spikes):

    // app/Listeners/AnalyticsAlertListener.php
    use Spatie\Analytics\Facades\Analytics;
    use Spatie\Analytics\Period;
    
    class AnalyticsAlertListener
    {
        public function handle()
        {
            $data = Analytics::fetchVisitorsAndPageViews(Period::today());
            $today = $data->first();
            $yesterday = Analytics::fetchVisitorsAndPageViews(Period::yesterday())->first();
    
            if ($today['activeUsers'] > $yesterday['activeUsers'] * 1.5) {
                // Send alert
            }
        }
    }
    
  4. Testing

    • Use the fake() method to mock responses in tests:
      Analytics::fake([
          ['pageTitle' => 'Home', 'screenPageViews' => 1000],
          ['pageTitle' => 'About', 'screenPageViews' => 500],
      ]);
      
    • Assert specific method calls:
      Analytics::shouldReceive('fetchMostVisitedPages')
          ->once()
          ->andReturn(collect([...]));
      

---
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.
codraw/framework-extra-bundle
codraw/messenger
codraw/security
codraw/mailer
codraw/contracts
codraw/profiling
codraw/dependency-injection
codraw/tester
codraw/core
nexmo/api-specification
capell-app/block-library
axium/identity
cetria/laravel-dummy-models
cetria/reflection-helper
agropredict/sso-auth-bundle
evolvestudio/spam-protection
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony