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 Data Laravel Package

google/analytics-data

Idiomatic PHP client for the Google Analytics Data API (GA4). Query reports, audience exports, and more via REST or gRPC. Install with Composer (google/analytics-data) and authenticate using Google Cloud credentials. Part of Google Cloud PHP (beta).

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require google/analytics-data
    

    Ensure your project uses PHP 8.1+ (recommended) and has ext-grpc if using gRPC.

  2. Authentication: Use the Google Cloud PHP Auth Guide. For Laravel, store credentials in .env (e.g., GOOGLE_APPLICATION_CREDENTIALS=path/to/service-account.json) or use the Laravel Google Auth package.

  3. First Query:

    use Google\Analytics\Data\V1beta\BetaAnalyticsDataClient;
    use Google\Analytics\Data\V1beta\RunReportRequest;
    
    $client = new BetaAnalyticsDataClient();
    $request = (new RunReportRequest())
        ->setProperty('properties/YOUR_PROPERTY_ID')
        ->setDateRanges(['startDate:7daysAgo', 'endDate:today'])
        ->setDimensions(['country'])
        ->setMetrics(['activeUsers']);
    
    $response = $client->runReport($request);
    
  4. Key Files:

    • vendor/google/analytics-data/src/ for core classes.
    • API Reference for method signatures.

Implementation Patterns

Core Workflows

1. Reporting

  • Basic Report:

    $report = $client->runReport($request);
    $rows = $report->getRows();
    
  • Pivot Reports:

    $pivotRequest = (new RunPivotReportRequest())
        ->setProperty('properties/YOUR_PROPERTY_ID')
        ->setDimensions(['country', 'deviceCategory'])
        ->setMetrics(['sessions']);
    $pivotReport = $client->runPivotReport($pivotRequest);
    
  • Async Reports (for large datasets):

    $task = $client->createReportTask($request);
    $report = $client->queryReportTask($task->getName());
    

2. Audience Management

  • List Audiences:
    $audienceLists = $client->listAudienceLists('properties/YOUR_PROPERTY_ID');
    
  • Export Audiences:
    $export = $client->createAudienceExport([
        'name' => 'properties/YOUR_PROPERTY_ID/audienceExports/EXPORT_ID',
        'audienceId' => 'AUDIENCE_ID',
        'destination' => ['bigqueryDestination' => ['datasetId' => 'DATASET']],
    ]);
    

3. Quotas & Limits

  • Check remaining quota:
    $quota = $client->getPropertyQuotasSnapshot('properties/YOUR_PROPERTY_ID');
    $remaining = $quota->getQuotaStatuses()[0]->getRemaining();
    

4. Laravel Integration

  • Service Provider:
    // app/Providers/AnalyticsServiceProvider.php
    public function register()
    {
        $this->app->singleton(BetaAnalyticsDataClient::class, function ($app) {
            return new BetaAnalyticsDataClient();
        });
    }
    
  • Facade (Optional):
    // app/Facades/Analytics.php
    public static function runReport($request)
    {
        return app(BetaAnalyticsDataClient::class)->runReport($request);
    }
    

5. Caching Responses

Use Laravel’s cache to store frequent reports:

$cacheKey = 'analytics_report_' . md5($request->serializeToJsonString());
return Cache::remember($cacheKey, now()->addHours(1), function () use ($client, $request) {
    return $client->runReport($request);
});

6. Error Handling

Wrap API calls in a try-catch:

try {
    $response = $client->runReport($request);
} catch (Google\ApiCore\ApiException $e) {
    Log::error('Analytics API Error: ' . $e->getMessage());
    return response()->json(['error' => 'Failed to fetch analytics'], 500);
}

Gotchas and Tips

Pitfalls

  1. Authentication:

    • Never hardcode credentials in your code. Use environment variables or Laravel’s env() helper.
    • Service Account Scopes: Ensure your service account has the https://www.googleapis.com/auth/analytics.readonly scope for read operations.
  2. Quota Limits:

    • The API enforces quota limits. Monitor sampling_metadatas in responses to avoid hitting limits.
    • Example quota check:
      if ($response->getMetadata()->getSamplingMetadatas()[0]->getSampledQuota()) {
          Log::warning('Report was sampled due to quota limits.');
      }
      
  3. Date Ranges:

    • Use ISO 8601 format (e.g., startDate:2023-01-01, endDate:2023-01-31).
    • Relative dates (e.g., 7daysAgo) are supported but may behave unexpectedly in cached reports.
  4. Deprecations:

    • The v1alpha surface is deprecated. Use v1beta for new projects.
    • Methods like credentials in client options are deprecated. Use Application Default Credentials instead.
  5. gRPC vs REST:

    • gRPC offers better performance for streaming but requires ext-grpc. Fall back to REST if gRPC is unavailable:
      $client = new BetaAnalyticsDataClient(['grpc' => false]);
      
  6. Empty Filters:

    • Use EmptyFilter to match all rows when no filter is needed:
      $request->setFilter('filter:emptyFilter');
      

Debugging Tips

  1. Enable Debugging: Set the GAX_DEBUG environment variable to log gRPC/REST traffic:

    export GAX_DEBUG=debug
    

    Or in Laravel’s .env:

    GAX_DEBUG=debug
    
  2. Validate Requests: Use serializeToJsonString() to inspect request payloads:

    Log::debug('Analytics Request:', ['payload' => $request->serializeToJsonString()]);
    
  3. Common Errors:

    • INVALID_ARGUMENT: Validate property IDs, date ranges, and dimension/metric names against Google’s documentation.
    • PERMISSION_DENIED: Ensure your service account has access to the Google Analytics property.
  4. Sampling: If sampling_metadatas indicates sampling, consider:

    • Reducing the date range.
    • Using samplingLevel: NO_SAMPLING (if quota allows):
      $request->setSamplingLevel('NO_SAMPLING');
      

Performance Tips

  1. Batch Requests: Combine multiple reports into a single API call where possible (e.g., using RunPivotReport for multi-dimensional data).

  2. Async Reports: For large datasets, use CreateReportTask and poll the result:

    $task = $client->createReportTask($request);
    while (true) {
        $report = $client->queryReportTask($task->getName());
        if ($report->getStatus() === 'COMPLETE') {
            break;
        }
        sleep(5); // Poll every 5 seconds
    }
    
  3. Caching: Cache responses aggressively for static reports (e.g., daily metrics):

    Cache::forever('analytics_daily_metrics', $response);
    

Extension Points

  1. Custom Metrics/Dimensions: Extend the Dimension and Metric classes to add project-specific fields:

    class CustomDimension extends \Google\Analytics\Data\V1beta\Dimension {
        public function __construct(string $name, string $value) {
            parent::__construct();
            $this->setName($name);
            $this->setValue($value);
        }
    }
    
  2. Middleware: Add request/response middleware for logging or transformation:

    $client->addMiddleware(function ($request, $next) {
        Log::info('Analytics Request:', ['method' => $request->getMethod()]);
        return $next($request);
    });
    
  3. Laravel Events: Dispatch events for analytics data (e.g., AnalyticsReportFetched):

    event(new AnalyticsReportFetched($response));
    
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