GA4 Analytics for Laravel

Build Google Analytics Data API queries in Laravel with ease!

Methods currently return an instance of Gtmassey\LaravelAnalytics\ResponseData, containing the dimension and metric headers, and results in rows.

Installation

Via Composer:

composer require gtmassey/laravel-analytics

Setup

To use this package, you must have a Google Cloud Service Accounts Credential.

If you do not have a project set up on Google Cloud Platform, visit console.cloud.google.com/projectcreate to create a new project.

Once you have a project, make sure you have selected that project in the top left corner of the console.

Screen Shot 2022-11-30 at 2 22 35 PM

Select APIs & Services from the quick access cards on the dashboard.

Screen Shot 2022-11-30 at 2 22 54 PM

Make sure you have Google Analytics Data API enabled. NOTE: this is NOT the same API as Google Analytics API. The Data API is the required API for this package. If you do not have the Google Analytics Data API enabled, you can add it to your Cloud Console account by clicking “enable APIs and Services”

Screen Shot 2022-11-30 at 2 23 25 PM

You can search for the Google Analytics Data API and enable it through the Google API Library

Screen Shot 2022-11-30 at 2 24 09 PM
Screen Shot 2022-11-30 at 2 24 21 PM

Once enabled, select the Google Analytics Data API from the list of APIs, and click the Credentials tab.

Screen Shot 2022-11-30 at 2 24 48 PM

If you already have a service account set up with this API, you can skip the next step.

Click the Create Credentials button, and select Service Account.

Screen Shot 2022-11-30 at 2 26 24 PM

Select the role you want to assign to the service account. For this package, the minimum role is the Viewer role.

Once your service account has been created, click on the account to go to the IAM & Admin section of Google Cloud Console.

In the Service Accounts section of the IAM & Admin page, select the appropriate service account, and create a new JSON key for the account:

Screen Shot 2022-11-30 at 2 27 01 PM
Screen Shot 2022-11-30 at 2 27 14 PM

Once the key is created, download the JSON file and save it somewhere safe. You will need this file to use this package. If you lose this file, you will have to create a new service account. Google does not let you re-issue keys.

You can use these credentials in several ways:

Credentials As ENV:

This is ideal setup if you’re using only one service account for your application.

Specify the path to the JSON file in your .env file:

GOOGLE_APPLICATION_CREDENTIALS=/path/to/credentials.json

Credentials As JSON:

If you have multiple service accounts, you can instruct this package to use a specific one:

ANALYTICS_CREDENTIALS_USE_ENV=false
ANALYTICS_CREDENTIALS_FILE=/path/to/credentials.json

Credentials As Separate Values

You can also specify the credentials as separate values in your .env file:

ANALYTICS_CREDENTIALS_USE_ENV=false
ANALYTICS_CREDENTIALS_TYPE=service_account
ANALYTICS_CREDENTIALS_PROJECT_ID=...
ANALYTICS_CREDENTIALS_PRIVATE_KEY_ID=...
ANALYTICS_CREDENTIALS_PRIVATE_KEY=...
ANALYTICS_CREDENTIALS_CLIENT_EMAIL=...
ANALYTICS_CREDENTIALS_CLIENT_ID=...
ANALYTICS_CREDENTIALS_AUTH_URI=...
ANALYTICS_CREDENTIALS_TOKEN_URI=...
ANALYTICS_CREDENTIALS_AUTH_PROVIDER_X509_CERT_URL=...
ANALYTICS_CREDENTIALS_CLIENT_X509_CERT_URL=...

Finally, open Google Analytics, and copy the property ID for the property you want to query. You will need this ID to use this package.

Set the property ID in your .env file.

ANALYTICS_PROPERTY_ID="XXXXXXXXX"

Now you’re ready to start!

Usage

Once installation is complete, you can run Google Analytics Data API queries in your application.

All Google Analytics Data API queries require a date range to be run. Use the Period class to generate a period of time for the query.

Query Builder:

use Gtmassey\LaravelAnalytics\Request\Dimensions;
use Gtmassey\LaravelAnalytics\Request\Metrics;
use Gtmassey\LaravelAnalytics\Analytics;
use Gtmassey\Period\Period;
use Carbon\Carbon;

$report = Analytics::query()
    ->setMetrics(fn(Metrics $metrics) => $metrics
        ->active1DayUsers()
        ->active7DayUsers()
        ->active28DayUsers()
    )
    ->forPeriod(Period::defaultPeriod())
    ->run();

$report2 = Analytics::query()
    ->setMetrics(fn(Metrics $metrics) => $metrics->sessions())
    ->setDimensions(
        fn(Dimensions $dimensions) => $dimensions->pageTitle()
    )->forPeriod(
        Period::create(
            Carbon::now()->subDays(30), 
            Carbon::now()
        )
    )->run();

Filtering:

Filtering closely follows Google Analytics Data API documentation, but is built with a bit of convenience and fluid interface in mind. You can filter your query by using dimensionFilter() and metricFilter() methods. These methods accept a callback that receives an instance of Gtmassey\LaravelAnalytics\Request\Filters\FilterExpression class. The class provides a set of methods to build your filter:

  • filter() – generic filter method that accepts a dimension or metric name and a filter callback
  • filterDimension() – filter method that accepts a dimension object via callback and a filter callback
  • filterMetric() – filter method that accepts a metric object via callback and a filter callback
  • not() – negates the filter
  • andGroup() – creates a group of filters that are combined with AND operator
  • orGroup() – creates a group of filters that are combined with OR operator

You can check Gtmassey\LaravelAnalytics\Request\Filters\Filter class for a list of available filter callback methods.

filter() method:

use Gtmassey\LaravelAnalytics\Request\Dimensions;
use Gtmassey\LaravelAnalytics\Request\Filters\Filter;
use Gtmassey\LaravelAnalytics\Request\Filters\FilterExpression;
use Gtmassey\LaravelAnalytics\Request\Metrics;
use Gtmassey\LaravelAnalytics\Analytics;
use Gtmassey\Period\Period;

$report = Analytics::query()
    ->setMetrics(fn(Metrics $metrics) => $metrics->sessions())
    ->setDimensions(fn(Dimensions $dimensions) => $dimensions->pageTitle())
    ->forPeriod(Period::defaultPeriod())
    ->dimensionFilter(fn(FilterExpression $filterExpression) => $filterExpression
        ->filter('pageTitle', fn(Filter $filter) => $filter->exact('Home'))
    )->run();