About this project

laravel-analytics is a Laravel package developed by Spatie for retrieving analytics data from Google Analytics using the Google Analytics Data API. ## Capabilities The package exposes a facade `Spatie\Analytics\Facades\Analytics` with several convenience methods: - `fetchMostVisitedPages(Period $period, int $maxResults = 20)` — returns fullPageUrl, pageTitle, screenPageViews - `fetchVisitorsAndPageViews(Period $period)` — returns activeUsers and screenPageViews - `fetchVisitorsAndPageViewsByDate(Period $period)` — adds a date key per row - `fetchTotalVisitorsAndPageViews(Period $period)` — aggregates totals per date - `fetchTopReferrers(Period $period, int $maxResults = 20)` — returns pageReferrer and screenPageViews - `fetchUserTypes(Period $period)` — returns new vs returning users - `fetchTopBrowsers(Period $period, int $maxResults = 10)` — returns browser and screenPageViews - `fetchTopCountries(Period $period, int $maxResults = 10)` — returns country and screenPageViews - `fetchTopOperatingSystems(Period $period, int $maxResults = 10)` — returns operatingSystem and screenPageViews - `get(Period $period, array $metrics, array $dimensions = [], ...)` — arbitrary GA4 queries with ordering, pagination, dimension filters, and metric filters All methods return an `Illuminate\Support\Collection` of arrays. ## Installation ```bash composer require spatie/laravel-analytics ``` Optionally publish the configuration: ```bash php artisan vendor:publish --tag="analytics-config" ``` The published config at `config/analytics.php` requires: - `property_id`: your GA4 property ID - `service_account_credentials_json`: path to a service account JSON key, or an array containing the credentials - `cache_lifetime_in_minutes`: defaults to 1440 minutes; set to 0 to disable caching - `cache.store` and optional prefix/lifetime for the underlying cache ## Authentication setup 1. Create a project in [Google Cloud Console](https://console.developers.google.com/apis) 2. Enable the **Google Analytics Data API** in the API Library 3. Create a service account and download its JSON key 4. Share your GA4 property with the service account email at minimum the Analyst role 5. Store the JSON file securely and point the config at it ## Periods The `Spatie\Analytics\Period` class supports: ```php Period::days(7) Period::months(6) Period::create($startDate, $endDate) // accepts Carbon instances ``` ## Testing with fakes The facade provides a `fake` method for unit and feature tests: ```php use Spatie\Analytics\Facades\Analytics; Analytics::fake(); // or with predefined responses Analytics::fake([ ['pageTitle' => 'Home', 'activeUsers' => 10, 'screenPageViews' => 20], ]); ``` Package tests can be run with: ```bash vendor/bin/pest ``` ## License MIT licensed. See the repository LICENSE for details.