Try Live
Add Docs
Rankings
Pricing
Docs
Install
Install
Docs
Pricing
More...
More...
Try Live
Rankings
Enterprise
Create API Key
Add Docs
Laravel Analytics
https://github.com/spatie/laravel-analytics
Admin
This package allows you to easily retrieve data from Google Analytics, providing methods to fetch
...
Tokens:
13,145
Snippets:
86
Trust Score:
-
Update:
3 months ago
Context
Skills
Chat
Benchmark
72.6
Suggestions
Latest
Show doc for...
Code
Info
Show Results
Context Summary (auto-generated)
Raw
Copy
Link
# Laravel Analytics Laravel Analytics is a Spatie package that provides an elegant interface for retrieving data from Google Analytics 4 (GA4) using the Google Analytics Data API. This Laravel package simplifies the process of querying analytics data by offering fluent methods for common reporting needs such as page views, visitor statistics, referrer information, and custom metric queries. The package integrates seamlessly with Laravel's service container and includes built-in caching support to optimize API usage and response times. The package is designed to work with GA4 properties and requires authentication through Google service account credentials. It provides type-safe collection responses, support for custom date periods, advanced filtering capabilities, and comprehensive testing utilities. All methods return Laravel Collections containing structured arrays with the requested metrics and dimensions, making it easy to integrate analytics data into your application's views, APIs, or data processing pipelines. ## Installation and Configuration Installing and configuring the package ```bash # Install via Composer composer require spatie/laravel-analytics # Publish configuration file php artisan vendor:publish --tag="analytics-config" ``` ```php // config/analytics.php return [ // Your GA4 property ID 'property_id' => env('ANALYTICS_PROPERTY_ID'), // Path to service account credentials JSON file 'service_account_credentials_json' => storage_path('app/analytics/service-account-credentials.json'), // Cache responses for 24 hours (in minutes) 'cache_lifetime_in_minutes' => 60 * 24, // Cache store configuration 'cache' => [ 'store' => 'file', ], ]; ``` ```bash # Set environment variables ANALYTICS_PROPERTY_ID=123456789 ``` ## Fetch Most Visited Pages Retrieve the top pages by page views for a given period ```php use Spatie\Analytics\Facades\Analytics; use Spatie\Analytics\Period; // Get top 20 most visited pages for the last 7 days $pages = Analytics::fetchMostVisitedPages(Period::days(7), maxResults: 20); foreach ($pages as $page) { echo "URL: {$page['fullPageUrl']}\n"; echo "Title: {$page['pageTitle']}\n"; echo "Views: {$page['screenPageViews']}\n"; echo "---\n"; } // Result structure: // Collection of arrays with keys: 'fullPageUrl', 'pageTitle', 'screenPageViews' // [ // ['fullPageUrl' => 'https://example.com/blog', 'pageTitle' => 'Blog', 'screenPageViews' => 1523], // ['fullPageUrl' => 'https://example.com/about', 'pageTitle' => 'About', 'screenPageViews' => 892], // ... // ] ``` ## Fetch Visitors and Page Views Get active users and page view metrics for a time period ```php use Spatie\Analytics\Facades\Analytics; use Spatie\Analytics\Period; // Get visitor and page view data for the last 30 days $data = Analytics::fetchVisitorsAndPageViews(Period::days(30), maxResults: 10); foreach ($data as $item) { echo "Page: {$item['pageTitle']}\n"; echo "Active Users: {$item['activeUsers']}\n"; echo "Page Views: {$item['screenPageViews']}\n"; echo "---\n"; } // Returns Collection of arrays with keys: 'pageTitle', 'activeUsers', 'screenPageViews' ``` ## Fetch Visitors and Page Views by Date Get daily breakdown of visitors and page views ```php use Spatie\Analytics\Facades\Analytics; use Spatie\Analytics\Period; // Get daily visitor data for the last 14 days $dailyData = Analytics::fetchVisitorsAndPageViewsByDate(Period::days(14), maxResults: 50); foreach ($dailyData as $day) { echo "Date: {$day['date']->format('Y-m-d')}\n"; echo "Page: {$day['pageTitle']}\n"; echo "Active Users: {$day['activeUsers']}\n"; echo "Page Views: {$day['screenPageViews']}\n"; echo "---\n"; } // Returns Collection with keys: 'pageTitle', 'date' (Carbon instance), 'activeUsers', 'screenPageViews' ``` ## Fetch Total Visitors and Page Views Get aggregated visitor metrics by date ```php use Spatie\Analytics\Facades\Analytics; use Spatie\Analytics\Period; // Get total visitors per day for the last 7 days $totals = Analytics::fetchTotalVisitorsAndPageViews(Period::days(7)); foreach ($totals as $day) { echo "Date: {$day['date']->format('Y-m-d')}\n"; echo "Total Active Users: {$day['activeUsers']}\n"; echo "Total Page Views: {$day['screenPageViews']}\n"; } // Returns Collection with keys: 'date' (Carbon instance), 'activeUsers', 'screenPageViews' ``` ## Fetch Top Referrers Get traffic sources and referrer information ```php use Spatie\Analytics\Facades\Analytics; use Spatie\Analytics\Period; // Get top 10 referrers for the last month $referrers = Analytics::fetchTopReferrers(Period::months(1), maxResults: 10); foreach ($referrers as $referrer) { echo "Referrer: {$referrer['pageReferrer']}\n"; echo "Page Views: {$referrer['screenPageViews']}\n"; echo "---\n"; } // Returns Collection with keys: 'pageReferrer', 'screenPageViews' // Example values: 'google', 'facebook.com', '(direct)', etc. ``` ## Fetch User Types Get breakdown of new vs returning visitors ```php use Spatie\Analytics\Facades\Analytics; use Spatie\Analytics\Period; // Get user type distribution for the last 30 days $userTypes = Analytics::fetchUserTypes(Period::days(30)); foreach ($userTypes as $type) { echo "User Type: {$type['newVsReturning']}\n"; echo "Active Users: {$type['activeUsers']}\n"; } // Returns Collection with keys: 'newVsReturning' ('new' or 'returning'), 'activeUsers' // Example output: // User Type: new, Active Users: 1523 // User Type: returning, Active Users: 892 ``` ## Fetch Top Browsers Get browser usage statistics ```php use Spatie\Analytics\Facades\Analytics; use Spatie\Analytics\Period; // Get top 10 browsers for the last 7 days $browsers = Analytics::fetchTopBrowsers(Period::days(7), maxResults: 10); foreach ($browsers as $browser) { echo "Browser: {$browser['browser']}\n"; echo "Page Views: {$browser['screenPageViews']}\n"; } // Returns Collection with keys: 'browser', 'screenPageViews' // Example browsers: 'Chrome', 'Safari', 'Firefox', 'Edge' ``` ## Fetch Top Countries Get geographic distribution of visitors ```php use Spatie\Analytics\Facades\Analytics; use Spatie\Analytics\Period; // Get top 15 countries for the last 30 days $countries = Analytics::fetchTopCountries(Period::days(30), maxResults: 15); foreach ($countries as $country) { echo "Country: {$country['country']}\n"; echo "Page Views: {$country['screenPageViews']}\n"; } // Returns Collection with keys: 'country', 'screenPageViews' // Example countries: 'United States', 'United Kingdom', 'Canada', etc. ``` ## Fetch Top Operating Systems Get operating system usage statistics ```php use Spatie\Analytics\Facades\Analytics; use Spatie\Analytics\Period; // Get top operating systems for the last 14 days $systems = Analytics::fetchTopOperatingSystems(Period::days(14), maxResults: 10); foreach ($systems as $os) { echo "OS: {$os['operatingSystem']}\n"; echo "Page Views: {$os['screenPageViews']}\n"; } // Returns Collection with keys: 'operatingSystem', 'screenPageViews' // Example systems: 'Windows', 'Macintosh', 'Linux', 'Android', 'iOS' ``` ## Custom Period Queries Create custom date ranges for analytics queries ```php use Spatie\Analytics\Period; use Carbon\Carbon; // Last 7 days $period = Period::days(7); // Last 3 months $period = Period::months(3); // Last 2 years $period = Period::years(2); // Custom date range $startDate = Carbon::parse('2024-01-01'); $endDate = Carbon::parse('2024-12-31'); $period = Period::create($startDate, $endDate); // Use with any Analytics method $data = Analytics::fetchMostVisitedPages($period); ``` ## Advanced Custom Queries Execute custom queries with metrics, dimensions, and filters ```php use Spatie\Analytics\Facades\Analytics; use Spatie\Analytics\Period; use Spatie\Analytics\OrderBy; use Google\Analytics\Data\V1beta\Filter; use Google\Analytics\Data\V1beta\FilterExpression; use Google\Analytics\Data\V1beta\Filter\StringFilter; use Google\Analytics\Data\V1beta\Filter\StringFilter\MatchType; // Custom query with multiple metrics and dimensions $data = Analytics::get( period: Period::days(30), metrics: ['activeUsers', 'screenPageViews', 'sessions'], dimensions: ['city', 'country', 'date'], maxResults: 50, orderBy: [ OrderBy::dimension('date', descending: true), OrderBy::metric('activeUsers', descending: true), ], offset: 0, keepEmptyRows: false ); // With dimension filter (filter by specific event name) $dimensionFilter = new FilterExpression([ 'filter' => new Filter([ 'field_name' => 'eventName', 'string_filter' => new StringFilter([ 'match_type' => MatchType::EXACT, 'value' => 'click', ]), ]), ]); $clickEvents = Analytics::get( period: Period::days(7), metrics: ['eventCount'], dimensions: ['eventName', 'pagePath'], maxResults: 100, dimensionFilter: $dimensionFilter ); foreach ($clickEvents as $event) { echo "Event: {$event['eventName']}\n"; echo "Path: {$event['pagePath']}\n"; echo "Count: {$event['eventCount']}\n"; } ``` ## Advanced Filtering with Numeric Filters Filter results based on metric values ```php use Spatie\Analytics\Facades\Analytics; use Spatie\Analytics\Period; use Google\Analytics\Data\V1beta\Filter; use Google\Analytics\Data\V1beta\FilterExpression; use Google\Analytics\Data\V1beta\Filter\NumericFilter; use Google\Analytics\Data\V1beta\NumericValue; use Google\Analytics\Data\V1beta\Filter\NumericFilter\Operation; // Get pages with more than 100 page views $metricFilter = new FilterExpression([ 'filter' => new Filter([ 'field_name' => 'screenPageViews', 'numeric_filter' => new NumericFilter([ 'operation' => Operation::GREATER_THAN, 'value' => new NumericValue([ 'int64_value' => 100, ]), ]), ]), ]); $popularPages = Analytics::get( period: Period::days(30), metrics: ['screenPageViews', 'activeUsers'], dimensions: ['pageTitle', 'fullPageUrl'], maxResults: 50, metricFilter: $metricFilter ); foreach ($popularPages as $page) { echo "Title: {$page['pageTitle']}\n"; echo "Views: {$page['screenPageViews']}\n"; echo "Users: {$page['activeUsers']}\n"; } ``` ## Realtime Analytics Queries Get real-time analytics data for current activity ```php use Spatie\Analytics\Facades\Analytics; use Spatie\Analytics\Period; // Get real-time active users and page views $realtimeData = Analytics::getRealtime( period: Period::days(1), metrics: ['activeUsers', 'screenPageViews'], dimensions: ['city', 'pageTitle'], maxResults: 20 ); foreach ($realtimeData as $item) { echo "Location: {$item['city']}\n"; echo "Page: {$item['pageTitle']}\n"; echo "Current Users: {$item['activeUsers']}\n"; } // Returns real-time data for the specified minute range ``` ## Pagination with Offset Handle large result sets with pagination ```php use Spatie\Analytics\Facades\Analytics; use Spatie\Analytics\Period; // Get first page (results 1-50) $page1 = Analytics::fetchMostVisitedPages( period: Period::days(30), maxResults: 50, offset: 0 ); // Get second page (results 51-100) $page2 = Analytics::fetchMostVisitedPages( period: Period::days(30), maxResults: 50, offset: 50 ); // Get third page (results 101-150) $page3 = Analytics::fetchMostVisitedPages( period: Period::days(30), maxResults: 50, offset: 100 ); // Combine results if needed $allPages = $page1->merge($page2)->merge($page3); ``` ## Testing with Fakes Test your application without making actual API calls ```php use Spatie\Analytics\Facades\Analytics; use Spatie\Analytics\Period; // In your test file test('analytics dashboard displays data', function () { // Arrange - Fake Analytics with expected data Analytics::fake([ [ 'pageTitle' => 'Homepage', 'activeUsers' => 150, 'screenPageViews' => 500, ], [ 'pageTitle' => 'Blog Post', 'activeUsers' => 80, 'screenPageViews' => 250, ], ]); // Act - Make request to your analytics dashboard $response = $this->actingAs($user)->get('/dashboard/analytics'); // Assert - Verify response $response->assertStatus(200); $response->assertSee('Homepage'); $response->assertSee('150'); }); // Fake with empty results test('handles no analytics data gracefully', function () { Analytics::fake(collect([])); $response = $this->get('/dashboard/analytics'); $response->assertStatus(200); $response->assertSee('No data available'); }); ``` ## Dynamic Property ID Configuration Switch between different GA4 properties at runtime ```php use Spatie\Analytics\Facades\Analytics; use Spatie\Analytics\Period; // Get default property ID $propertyId = Analytics::getPropertyId(); echo "Current Property: {$propertyId}\n"; // Switch to different property Analytics::setPropertyId('987654321'); // Now queries use the new property $data = Analytics::fetchMostVisitedPages(Period::days(7)); // Switch back to original property Analytics::setPropertyId($propertyId); ``` ## Laravel Integration Example Complete example integrating Analytics into a Laravel controller ```php namespace App\Http\Controllers; use Spatie\Analytics\Facades\Analytics; use Spatie\Analytics\Period; use Illuminate\Http\Request; class AnalyticsDashboardController extends Controller { public function index() { try { // Get various analytics data $mostVisited = Analytics::fetchMostVisitedPages(Period::days(7), maxResults: 10); $topReferrers = Analytics::fetchTopReferrers(Period::days(7), maxResults: 5); $userTypes = Analytics::fetchUserTypes(Period::days(30)); $dailyStats = Analytics::fetchTotalVisitorsAndPageViews(Period::days(14)); return view('dashboard.analytics', [ 'mostVisited' => $mostVisited, 'topReferrers' => $topReferrers, 'userTypes' => $userTypes, 'dailyStats' => $dailyStats, ]); } catch (\Exception $e) { return view('dashboard.analytics', [ 'error' => 'Failed to load analytics data: ' . $e->getMessage(), ]); } } public function api() { $period = Period::days(30); return response()->json([ 'pages' => Analytics::fetchMostVisitedPages($period, maxResults: 20), 'countries' => Analytics::fetchTopCountries($period, maxResults: 10), 'browsers' => Analytics::fetchTopBrowsers($period, maxResults: 5), ]); } } ``` ## Summary Laravel Analytics provides a comprehensive solution for integrating Google Analytics 4 data into Laravel applications. The package excels at common analytics tasks such as tracking page views, monitoring visitor behavior, analyzing traffic sources, and generating custom reports. With built-in caching, the package minimizes API calls and optimizes performance while providing fresh data when needed. The fluent API design makes it simple to fetch analytics data with just a few lines of code, returning Laravel Collections that integrate seamlessly with Blade templates, API responses, and data processing workflows. The package is particularly valuable for building analytics dashboards, generating periodic reports, monitoring application performance, and making data-driven decisions. Advanced features like custom queries with filters, real-time data access, pagination support, and comprehensive testing utilities make it suitable for both simple implementations and complex analytics requirements. Whether you need basic page view statistics or sophisticated custom queries with multiple dimensions and metrics, Laravel Analytics provides the tools to efficiently retrieve and process Google Analytics data within your Laravel application.