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.
Installation:
composer require spatie/analytics-statistics
For Laravel 5, use spatie/laravel-analytics instead (this package is legacy).
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
Publish Config (if needed):
php artisan vendor:publish --provider="Spatie\AnalyticsStatistics\AnalyticsStatisticsServiceProvider"
Configure in config/analytics-statistics.php.
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',
]);
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',
]);
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
}
Caching Responses: Cache frequent queries to reduce API calls:
$stats = AnalyticsStatistics::remember('daily_sessions', now()->addHours(1), function () {
return AnalyticsStatistics::get('ga:sessions', [...]);
});
Integration with Laravel:
Bind the service to the container in AppServiceProvider:
$this->app->singleton(AnalyticsStatistics::class, function () {
return new AnalyticsStatistics(config('analytics-statistics'));
});
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();
}
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',
]);
}
}
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'],
];
});
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
]);
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
}
Deprecated Package:
spatie/laravel-analytics for Laravel 5+ or consider modern alternatives like:
Authentication Issues:
GOOGLE_ANALYTICS_REFRESH_TOKEN is valid and has the correct scopes (https://www.googleapis.com/auth/analytics.readonly).Rate Limits:
$stats = AnalyticsStatistics::remember('monthly_report', now()->addDays(30), function () {
return AnalyticsStatistics::get('ga:sessions', [...]);
});
Date Ranges:
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");
}
Legacy PHP Support:
Enable Debugging:
Set debug to true in config/analytics-statistics.php to log raw API responses:
'debug' => env('APP_DEBUG', false),
Check API Responses:
Inspect the $stats->raw() property to debug malformed responses:
dd($stats->raw());
Validate Metrics/Dimensions: Use Google's Core Reporting API Dimension/Metric Explorer to verify valid metrics/dimensions.
Token Expiry:
If you get 401 Unauthorized, regenerate your OAuth2 tokens and update .env.
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,
]);
}
}
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
});
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']]
);
});
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');
How can I help you explore Laravel packages today?