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.
Pros:
fetchVisitorsAndPageViews, fetchMostVisitedPages), allowing selective adoption.Analytics:: facade, reducing boilerplate.get() method supports custom queries with metrics/dimensions/filters, enabling advanced use cases.Cons:
fetchVisitorsAndPageViews) can be integrated in hours with minimal code changes.get() method.google/apiclient) if not managed via Composer’s autoloader.Analytics Strategy:
Data Requirements:
Security & Compliance:
Performance:
cache_lifetime_in_minutes)? Shorter durations increase API calls but improve freshness.Maintenance:
Prerequisites:
Installation:
composer require spatie/laravel-analytics
php artisan vendor:publish --tag="analytics-config"
.env with ANALYTICS_PROPERTY_ID and GOOGLE_APPLICATION_CREDENTIALS (or publish the config file).Incremental Adoption:
fetchVisitorsAndPageViews) in non-critical paths.get() method.Testing:
Analytics::fake() method for unit/feature tests.google/apiclient (v2.0+). Ensure no version conflicts with other dependencies.redis or database in the config.Phase 1: Setup and Validation
fetchTotalVisitorsAndPageViews).Phase 2: Core Integration
Phase 3: Advanced Use Cases
get() method for niche metrics.Phase 4: Monitoring and Optimization
maxResults).spatie/laravel-analytics and google/apiclient for breaking changes.analytics.php config and its impact on caching/performance.try {
$data = Analytics::fetchVisitorsAndPageViews(Period::days(7));
} catch (\Google\ApiCore\ApiException $e) {
Log::error("Google Analytics API error: " . $e->getMessage());
// Fallback logic (e.g., cached data, user notification)
}
service_account_credentials_json path and permissions.cache_lifetime_in_minutes based on freshness needs (e.g., 5 minutes for dashboards, 24 hours for reports).offset, maxResults) in the get() method.| Failure Scenario | Impact | Mitigation |
|---|---|---|
| Google API downtime | No analytics data available. | Implement caching with stale-while-revalidate. Use fallback data or notifications. |
| Quota exceeded | Partial or no data for high-volume requests. | Monitor usage; request quota increases or optimize queries. |
| Invalid credentials | All API calls fail. | Automate credential rotation; alert on authentication errors. |
| GA4 property |
How can I help you explore Laravel packages today?