Library / SDK
spatie/laravel-analytics avatar
spatie/laravel-analytics

spatie/laravel-analytics: reading GA4 data inside a Laravel app

A Laravel package to retrieve pageviews and other data from Google Analytics

3,242 stars472 forksPHPMIT

At a glance

What is it?
The package wraps the Google Analytics Data API in a static facade and returns Laravel collections. It is a read layer for GA4, not a dashboard, and it needs a service account with property access before any of it works.
Who is it for?
Adopt it when you already run Laravel, already use GA4, and want pageview or visitor numbers inside your own controllers, scheduled commands or Blade views instead of in the Google Analytics interface. Do not adopt it if you need a dashboard out of the box, if your analytics lives somewhere other than Google, or if you cannot create a Google Cloud service account and grant it at least the Analyst role on the property.
Can I use it commercially?
Yes. MIT is a permissive licence: you can use, modify and sell software built on it, as long as you keep its copyright and licence notices.
Is it still maintained?
Yes. The repository last received commits 1 day ago.
What is it written in?
Mainly PHP, according to GitHub's language statistics.

Answers come from the project's GitHub data, last synced on September 29, 2026, and from our analysis. They are not legal advice.

Editorial analysis

What spatie/laravel-analytics actually does

This is a thin PHP client, not an analytics product. It sits between a Laravel application and the Google Analytics Data API, and its job is to turn the API's response into an Illuminate collection you can loop over in a controller, a scheduled command or a Blade template. The README describes it plainly: "Using this package you can easily retrieve data from Google Analytics."

The audience is narrow and specific. You are building or maintaining a Laravel app, your site already reports into Google Analytics, and you want numbers such as most visited pages or visitors and page views available in PHP rather than in a browser tab. The package does not collect anything itself. There is no tracking script, no middleware, no request logging. If nothing is sending data to GA4, this package will faithfully return empty results.

That distinction matters when people search for a Laravel analytics dashboard. The package gives you the data access layer; the dashboard is whatever you build on top of it.

The facade, the period object and the cache

The public surface shown in the README is a static facade, Spatie\Analytics\Facades\Analytics, paired with a Period value object. You describe a time window with Period::days(7) or Period::months(6) and pass it to a fetch method. The README's examples are fetchMostVisitedPages and fetchVisitorsAndPageViews, and it notes that most methods return an \Illuminate\Support\Collection.

Underneath, the package talks to the Google Analytics Data API using the Google client library, which is why the config file exposes a cache block. The comments in the published config explain the two layers: cache_lifetime_in_minutes controls how long the package caches Google API responses, and setting it to zero disables caching entirely, while the cache array configures the store the underlying Google_Client uses, with the config comment naming "lifetime" and "prefix" as optional parameters. The default is a file store and a lifetime of 60 * 24 minutes, one day.

That default is worth thinking about. A day-long cache means a page that renders yesterday's visitor count will keep rendering the same number for twenty-four hours. For a marketing page that is fine. For anything that reacts to traffic in the moment, you will want to lower cache_lifetime_in_minutes or set it to zero and accept the extra API calls.

Installing it and pulling your first GA4 numbers

Installation is a single Composer command. The package is on Packagist under the same name as the repository, and the README gives this as the install step.

bash
composer require spatie/laravel-analytics

The config file is optional, since the README says you can publish it with this command. Publishing gives you config/analytics.php, which is where property_id, service_account_credentials_json and the cache settings live.

bash
php artisan vendor:publish --tag="analytics-config"

The README then walks through the Google Cloud side: create or select a project, enable the Google Analytics Data API in the API Library, create a service account key of type JSON, and save that file at the path named in the service_account_credentials_json key of the config file. The config comment also notes you can pass the credentials as an array instead of a file path. The property ID goes into the ANALYTICS_PROPERTY_ID key in your .env file, copied from Analytics under Settings > Property Settings.

The last setup step is easy to miss. In Google Analytics, open Property Access Management, add the client_email value from the JSON file as a user, and the README says the Analyst role is enough. Without that grant, the API calls fail even though the credentials are valid.

With that done, the usage is two lines. This fetches visitors and page views for the last seven days and returns a collection.

php
use Spatie\Analytics\Facades\Analytics;
use Spatie\Analytics\Period;

$analyticsData = Analytics::fetchVisitorsAndPageViews(Period::days(7));

Where this package stops being the right tool

The credentials model is the first constraint. Access is granted per property to a service account email, and the README frames this as an admin task in the Google Analytics interface. If you are a developer without admin rights on the property, or the property belongs to a client who will not add an unfamiliar service account, the package is unusable regardless of how clean the PHP is. There is no OAuth flow for a signed-in user in the documented setup.

The second constraint is scope. The README presents a small set of convenience methods and states that most return collections. Anything beyond those methods means working with the underlying client, and the README does not document a general escape hatch for arbitrary Data API requests. If you need dimensions and metrics the package has no helper for, you are reading the Google client documentation, not this one.

The README is also silent on failure behaviour. It does not document what happens when the property ID is wrong, when the service account has been removed, or when the API quota is exhausted. It does not document rollback or retry. That silence is not a defect in itself, but it means error handling is your responsibility, and the cache default can hide a broken credential for up to a day after you change it.

How it compares with querying the Data API yourself

The honest alternative is using google/analytics-data or the google-api-php-client directly. The difference is not capability, since this package calls the same API. The difference is the shape of the code you write.

With the raw client you construct a RunReportRequest, choose dimensions and metrics by name, handle the response rows yourself, and decide how to map them into your application's structures. You get every dimension and metric the API exposes, including ones this package has no method for. You also write boilerplate for every report, and you own the caching decision entirely.

With spatie/laravel-analytics you trade that reach for named methods and a Period object, plus a config-driven cache that is already wired into the Google client. For the common questions (what are the most visited pages, how many visitors and page views in this window) that trade is clearly worth it. For anything more custom, the wrapper stops helping and you are back to the raw client anyway, with one more dependency in composer.json.

A second alternative is not using Google at all. If your reason for looking at this package is that you want request-level analytics inside your own application, a self-hosted tool or your own logging table answers a different question than GA4 does, and this package cannot substitute for either.

Maintenance, upgrades and the MIT licence

The repository is not archived, and the last push was on 2026-06-26. The most recent release listed is 5.7.1, published on 2026-04-28, following 5.7.0 on 2026-02-21 and 5.6.1 on 2025-11-26. The presence of an UPGRADE.md file at the repository root is the signal that matters for adopters: major versions have moved before, and the homepage points to the v5 release that added GA4 support, which means earlier versions targeted the older reporting model. If you are on a pre-v5 release, plan for a real migration rather than a composer update.

The upgrade cost going forward is mostly the cost of Google's side. The package depends on the Google Analytics Data API and on the google-api-php-client, so changes in either can force a release. Pinning a version and reading CHANGELOG.md before bumping is the cheap habit here.

The licence is MIT, as stated in the repository and in the README badge. That is permissive and compatible with closed-source Laravel applications. Two things sit outside the licence: the Google API terms you accept by using the Data API through a Cloud project, and the service account JSON itself, which the README explicitly says not to commit to git. Treat the credentials file as a secret with the same care as your .env. None of this is legal advice; if the data is personal data under a privacy regime, that question belongs to whoever handles compliance, not to the package.

Editorial conclusion

Adopt it when you already run Laravel, already use GA4, and want pageview or visitor numbers inside your own controllers, scheduled commands or Blade views instead of in the Google Analytics interface. Do not adopt it if you need a dashboard out of the box, if your analytics lives somewhere other than Google, or if you cannot create a Google Cloud service account and grant it at least the Analyst role on the property. Before writing code, verify three things: that the Google Analytics Data API is enabled on the Cloud project, that ANALYTICS_PROPERTY_ID holds the GA4 property ID and not a measurement ID, and that the service account JSON sits at the path in service_account_credentials_json or is passed as an array.

Frequently asked questions

Is spatie/laravel-analytics a dashboard, or just a data package?

It is a data package. The README describes retrieving data from Google Analytics and returning collections; there is no dashboard UI in the documented surface, so any interface has to be built in your Laravel application.

How do I install spatie/laravel-analytics?

Run composer require spatie/laravel-analytics, then optionally publish the config with php artisan vendor:publish --tag="analytics-config". After that you set ANALYTICS_PROPERTY_ID and place the service account JSON at the path in service_account_credentials_json.

What credentials does spatie/laravel-analytics need?

A Google Cloud service account key in JSON form, saved at the path named in the service_account_credentials_json key of the config file, or passed as an array. You also add the client_email from that file as a user on the GA4 property, where the README says the Analyst role is sufficient.

How long does spatie/laravel-analytics cache Google API responses?

The published config sets cache_lifetime_in_minutes to 60 * 24, one day, and its comments state that setting the value to zero disables caching entirely. The store used by the underlying Google client is configured separately under the cache key.

Official sources

  1. License: MIT
  2. Project website
  3. README
  4. Releases
  5. spatie/laravel-analytics on GitHub
Add this badge to your README

If you maintain this project, the badge below links readers to this analysis and shows its maintenance status from the daily GitHub snapshot. Paste the markdown into your README; add ?metric=license or ?metric=stars to the image URL for a different field.

Add this badge to your README

markdown
[![Hysen Labs](https://hysenlabs.com/badge/spatie-laravel-analytics.svg)](https://hysenlabs.com/projects/spatie-laravel-analytics)