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).
Pros:
v1beta → v1 migration path).Cons:
grpc-php extension), which may not be trivial for all Laravel deployments.ServiceProvider for dependency injection (e.g., AnalyticsDataClient singleton).RunReportTask) maps well to Laravel’s queue system (e.g., dispatch()).Route::get('/analytics', [AnalyticsController::class, 'fetch'])).Cache::remember) for frequent queries (e.g., RunReport).AnalyticsMetric, UserEvent) for business logic.analytics::reported) for downstream processing (e.g., notifications, ML pipelines)..env + Vault integration.RetryMiddleware or exponential backoff.pecl install grpc). Docker/Kubernetes deployments must include this.v1beta → v1 transitions.composer require, service binding).ApiException integrates cleanly with Laravel’s try/catch or App\Exceptions\Handler.RunReport vs. RunStreamingExport.| Laravel Component | Package Integration | Example Implementation |
|---|---|---|
| Service Container | Bind BetaAnalyticsDataClient as a singleton in AppServiceProvider. |
```php |
| // config/app.php | ||
| 'providers' => [ |
App\Providers\AnalyticsServiceProvider::class,
], // AppServiceProvider.php $this->app->singleton(BetaAnalyticsDataClient::class, fn() => new BetaAnalyticsDataClient());
| **Queues** | Dispatch async tasks (e.g., `RunReportTask`) to Laravel queues. | ```php
// AnalyticsJob.php
class RunAnalyticsReport implements ShouldQueue
{
public function handle()
{
$client->runReport($request);
}
}
dispatch(new RunAnalyticsReport($request));
``` |
| **Routing** | Expose analytics endpoints via Laravel routes. | ```php
Route::middleware('auth:api')->get('/analytics/report', [AnalyticsController::class, 'runReport']);
``` |
| **Caching** | Cache API responses (e.g., `RunReport`) with Laravel Cache. | ```php
return Cache::remember("analytics_{$propertyId}", now()->addHours(1), fn() =>
$client->runReport($request)
);
``` |
| **Events** | Dispatch events for analytics data (e.g., `AnalyticsReportGenerated`). | ```php
event(new AnalyticsReportGenerated($response));
``` |
| **Testing** | Mock `BetaAnalyticsDataClient` in PHPUnit. | ```php
$mock = $this->createMock(BetaAnalyticsDataClient::class);
$mock->method('runReport')->willReturn($mockResponse);
``` |
### **Migration Path**
1. **Phase 1: REST Integration (Low Risk)**
- Start with REST endpoints (e.g., `runReport`, `runPivotReport`) in a **feature flagged** branch.
- Use **Laravel’s HTTP client** (`\Illuminate\Support\Facades\Http`) as a fallback if gRPC is blocked.
- Example:
```php
$response = Http::withOptions(['auth' => [$serviceAccountJson]])->post(
'https://analyticsdata.googleapis.com/v1beta/properties/{property}/runs',
$request->toArray()
);
```
2. **Phase 2: gRPC Optimization (High Reward)**
- Enable gRPC in **staging** (Docker/K8s) and benchmark performance vs. REST.
- Migrate high-volume endpoints (e.g., streaming exports) to gRPC.
- Example:
```php
$client = new BetaAnalyticsDataClient([
'credentials' => $serviceAccountJson,
'grpc' => true, // Enable gRPC
]);
```
3. **Phase 3: Async Processing**
- Offload long-running tasks (e.g., `CreateReportTask`) to Laravel queues.
- Use **Google Cloud Tasks** for external async workflows if needed.
### **Compatibility**
- **Laravel Versions**:
- **Supported**: Laravel 9+ (PHP 8.1+). Tested with Laravel 10 in CI.
- **Legacy**: Laravel 8 may require polyfills for `Google\ApiCore` types.
- **PHP Extensions**:
- **Required**: `grpc` (for gRPC), `protobuf` (for Protobuf serialization).
- **Optional**: `curl` (fallback for REST-only deployments).
- **Google Cloud Dependencies**:
- **Service Account**: JSON key file (store in Laravel `.env` or `Vault`).
- **Scopes**: Ensure `https://www.googleapis.com/auth/analytics.readonly` (or `.edit`) is granted.
### **Sequencing**
1. **Setup**:
- Add `google/analytics-data` to `composer.json`.
- Configure authentication in `config/services.php`:
```php
'google_analytics' => [
'service_account' => env('GOOGLE_ANALYTICS_SERVICE_ACCOUNT'),
'use_grpc' => env('GOOGLE_ANALYTICS_USE_GRPC', false),
],
```
2. **Core Integration**:
- Implement `AnalyticsService` facade:
```php
// app/Facades/Analytics.php
public static function runReport($request) {
return app(BetaAnalyticsDataClient::class)->runReport($request);
}
```
3. **Feature Rollout**:
- Start with **read-only** endpoints (e.g., `runReport`).
- Gradually add **write operations** (e.g., `createAudienceExport`) if needed.
4. **Monitoring**:
- Log API responses/errors to **Laravel Log** or **Sentry**.
- Set up **Google Cloud Monitoring** for quota alerts.
---
## Operational Impact
### **Maintenance**
- **Pros**:
How can I help you explore Laravel packages today?