oriceon / laravel-analytics
Create and run Google Analytics Data API queries in Laravel
Requires
- php: ^8.1
- google/analytics-data: ^0.9.0
- illuminate/support: ^9.0|^10.0|^11.0
- nesbot/carbon: ^2.63|^3.1
- spatie/laravel-data: ^2.0|^4.6
- spatie/laravel-package-tools: ^1.16
Requires (Dev)
- laravel/pint: ^1.6
- nunomaduro/collision: ^6.4
- nunomaduro/larastan: ^2.4.1
- orchestra/testbench: ^7.15|^8.0.3
- phpstan/extension-installer: ^1.2
- phpstan/phpstan-deprecation-rules: ^1.1.2
- phpstan/phpstan-mockery: ^1.1.1
- phpstan/phpstan-phpunit: ^1.3.7
- phpunit/phpunit: ^9.6.3
- rregeer/phpunit-coverage-check: ^0.3.1
This package is auto-updated.
Last update: 2024-08-13 05:15:59 UTC
README
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
.
Table of Contents:
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.
Select APIs & Services from the quick access cards on the dashboard.
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"
You can search for the Google Analytics Data API and enable it through the Google API Library
Once enabled, select the Google Analytics Data API from the list of APIs, and click the Credentials tab.
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.
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:
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:
As ENV value (default)
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
As a separate JSON file
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
As a JSON string
If you don't want to store the credentials in a file, you can specify the JSON string directly in your .env file:
ANALYTICS_CREDENTIALS_USE_ENV=false ANALYTICS_CREDENTIALS_JSON="{type: service_account, project_id: ...}"
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=...
Warning Package will always prioritize
GOOGLE_APPLICATION_CREDENTIALS
env value over other options. If you want to use a separate service account, make sure to setANALYTICS_CREDENTIALS_USE_ENV=false
.
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 afilter callback
filterDimension()
- filter method that accepts a dimension object via callback and afilter callback
filterMetric()
- filter method that accepts a metric object via callback and afilter callback
not()
- negates the filterandGroup()
- creates a group of filters that are combined with AND operatororGroup()
- 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.
Examples:
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();
filterDimension()
method:
Using this method you can utilize Dimensions
class to fluently build your filter without having to know the exact dimension name that's used in the API.
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 ->filterDimension( dimensionsCallback: fn(Dimensions $dimensions) => $dimensions->pageTitle(), filter: fn(Filter $filter) => $filter->exact('Home') ) ) ->run();
filterMetric()
method:
Similar to filterDimension()
method, you can use this method and utilize Metrics
class to fluently build your filter without having to know the exact metric name that's used in the API.
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()) ->metricFilter(fn(FilterExpression $filterExpression) => $filterExpression ->filterMetric( metricsCallback: fn(Metrics $metrics) => $metrics->sessions(), filter: fn(Filter $filter) => $filter->greaterThanInt(100) ) ) ->run();
not()
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 ->not(fn(FilterExpression $filterExpression) => $filterExpression ->filter('pageTitle', fn(Filter $filter) => $filter ->exact('Home') ) ) ) ->run();
andGroup()
method:
use Gtmassey\LaravelAnalytics\Request\Dimensions; use Gtmassey\LaravelAnalytics\Request\Filters\Filter; use Gtmassey\LaravelAnalytics\Request\Filters\FilterExpression; use Gtmassey\LaravelAnalytics\Request\Filters\FilterExpressionList; 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->deviceCategory()->browser()) ->forPeriod(Period::defaultPeriod()) ->dimensionFilter(fn(FilterExpression $filterExpression) => $filterExpression ->andGroup(fn(FilterExpressionList $filterExpressionList) => $filterExpressionList ->filter('deviceCategory', fn(Filter $filter) => $filter ->exact('Mobile') ) ->filter('browser', fn(Filter $filter) => $filter ->exact('Chrome') ) ) ) ->run();
orGroup()
method:
use Gtmassey\LaravelAnalytics\Request\Dimensions; use Gtmassey\LaravelAnalytics\Request\Filters\Filter; use Gtmassey\LaravelAnalytics\Request\Filters\FilterExpression; use Gtmassey\LaravelAnalytics\Request\Filters\FilterExpressionList; 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->browser()) ->forPeriod(Period::defaultPeriod()) ->dimensionFilter(fn(FilterExpression $filterExpression) => $filterExpression ->orGroup(fn(FilterExpressionList $filterExpressionList) => $filterExpressionList ->filter('browser', fn(Filter $filter) => $filter ->exact('Firefox') ) ->filter('browser', fn(Filter $filter) => $filter ->exact('Chrome') ) ) ) ->run();
Advanced example:
You can mix all of the above methods to build a complex filter expression.
use Gtmassey\LaravelAnalytics\Request\Dimensions; use Gtmassey\LaravelAnalytics\Request\Filters\Filter; use Gtmassey\LaravelAnalytics\Request\Filters\FilterExpression; use Gtmassey\LaravelAnalytics\Request\Filters\FilterExpressionList; use Gtmassey\LaravelAnalytics\Request\Metrics; use Gtmassey\LaravelAnalytics\Analytics; use Gtmassey\Period\Period; $report = Analytics::query() ->setMetrics(fn(Metrics $metrics) => $metrics->sessions()->screenPageViews()) ->setDimensions(fn(Dimensions $dimensions) => $dimensions->browser()->deviceCategory()) ->forPeriod(Period::defaultPeriod()) ->dimensionFilter(fn(FilterExpression $filterExpression) => $filterExpression ->andGroup(fn(FilterExpressionList $filterExpressionList) => $filterExpressionList ->filter('browser', fn(Filter $filter) => $filter ->contains('safari') ) ->not(fn(FilterExpression $filterExpression) => $filterExpression ->filterDimension( dimensionsCallback: fn(Dimensions $dimensions) => $dimensions->deviceCategory(), filter: fn(Filter $filter) => $filter->contains('mobile') ) ) ) ) ->metricFilter(fn(FilterExpression $filterExpression) => $filterExpression ->orGroup(fn(FilterExpressionList $filterExpressionList) => $filterExpressionList ->filter('sessions', fn(Filter $filter) => $filter ->greaterThanInt(200) ) ->filterMetric( metricsCallback: fn(Metrics $metrics) => $metrics->sessions(), filter: fn(Filter $filter) => $filter->lessThanInt(100) ) ) ) ->run();
Default Reports:
getTopEvents()
$report = Analytics::getTopEvents();
This method returns the top events for the given period. It accepts a Gtmassey\Period\Period
object as an optional parameter.
If a Gtmassey\Period\Period
object is not passed, it will use the default period set in Gtmassey\Period\Period::defaultPeriod()
.
The method will return an instance of Gtmassey\LaravelAnalytics\Response\ResponseData
, which contains DimensionHeaders
, MetricHeaders
, Rows
, and additional metadata.
example output:
Gtmassey\LaravelAnalytics\Response\ResponseData { +dimensionHeaders: Spatie\LaravelData\DataCollection { +items: array:1 [ 0 => Gtmassey\LaravelAnalytics\Response\DimensionHeader { +name: "eventName" } ] } +metricHeaders: Spatie\LaravelData\DataCollection { +items: array:1 [ 0 => Gtmassey\LaravelAnalytics\Response\MetricHeader { +name: "eventCount" +type: "TYPE_INTEGER" } ] } +rows: Spatie\LaravelData\DataCollection { +items: array:6 [ 0 => Gtmassey\LaravelAnalytics\Response\Row { +dimensionValues: Spatie\LaravelData\DataCollection { +items: array:1 [ 0 => Gtmassey\LaravelAnalytics\Response\DimensionValue { +value: "page_view" } ] } +metricValues: Spatie\LaravelData\DataCollection { +items: array:1 [ 0 => Gtmassey\LaravelAnalytics\Response\MetricValue { +value: "1510" } ] } } 1 => Gtmassey\LaravelAnalytics\Response\Row {} 2 => Gtmassey\LaravelAnalytics\Response\Row {} 3 => Gtmassey\LaravelAnalytics\Response\Row {} 4 => Gtmassey\LaravelAnalytics\Response\Row {} 5 => Gtmassey\LaravelAnalytics\Response\Row {} ] } +totals: null +rowCount: 6 +metadata: Gtmassey\LaravelAnalytics\Response\Metadata {} +propertyQuota: null +kind: "analyticsData#runReport" }
getTopPages()
$report = Analytics::getTopPages();
This method returns the top pages for the given period. It accepts a Gtmassey\Period\Period
object as an optional parameter.
The pages along with the sessions for that page are listed in the Rows
property of the response.
getUserAcquisitionOverview()
$report = Analytics::getUserAcquisitionOverview();
This method returns the user acquisition overview for the given period. It accepts a Gtmassey\Period\Period
object as an optional parameter.
The method will return a ResponseData
object with the number of sessions by the session's primary acquisition source. Primary acquisition sources are either "direct", "Referral", "Organic Search", and "Organic Social".
getUserEngagement()
$report = Analytics::getUserEngagement();
This method returns a ResponseData
object without dimensions. The query only contains metrics. The ResponseData
object will contain:
- average session duration, in seconds
- number of engaged sessions
- number of sessions per user
- total number of sessions
Extensibility:
Custom metrics and dimensions:
You are not limited to the metrics and dimensions provided by this package. You can use any custom metrics and dimensions you have created in Google Analytics.
Create a new class that extends Gtmassey\LaravelAnalytics\Request\CustomMetric
or Gtmassey\LaravelAnalytics\Request\CustomDimension
and implement methods following this format:.
namespace App\Analytics; use Google\Analytics\Data\V1beta\Metric; use Gtmassey\LaravelAnalytics\Request\Metrics; class CustomMetrics extends Metrics { public function customMetric(): self { $this->metrics->push(new Metric(['name' => 'customEvent:parameter_name'])); return $this; } }
Bind the class in your AppServiceProvider
:
use Gtmassey\LaravelAnalytics\Request\Metrics; use App\Analytics\CustomMetrics; //use Gtmassey\LaravelAnalytics\Request\Dimensions; //use App\Analytics\CustomDimensions; public function boot() { $this->app->bind(Metrics::class, CustomMetrics::class); //$this->app->bind(Dimensions::class, CustomDimensions::class); }
Now you can use the custom metric in your query:
use App\Analytics\CustomMetrics; use Gtmassey\LaravelAnalytics\Analytics; use Gtmassey\LaravelAnalytics\Period; $report = Analytics::query() ->setMetrics(fn(CustomMetrics $metrics) => $metrics ->customMetric() ->sessions() ) ->forPeriod(Period::defaultPeriod()) ->run();
Reusable filters:
You can create reusable filters to use in your queries. Create a new class that extends Gtmassey\LaravelAnalytics\Analytics
and implement methods following this format:
namespace App\Analytics; use Gtmassey\LaravelAnalytics\Analytics; use Gtmassey\LaravelAnalytics\Request\Filters\Filter; use Gtmassey\LaravelAnalytics\Request\Filters\FilterExpression; use Gtmassey\LaravelAnalytics\Request\Metrics; class CustomAnalytics extends Analytics { public function onlySessionsAbove(int $count): static { $this->metricFilter(fn(FilterExpression $filterExpression) => $filterExpression ->filterMetric( metricsCallback: fn(Metrics $metrics) => $metrics->sessions(), filter: fn(Filter $filter) => $filter->greaterThanInt($count), ) ); return $this; } }
Bind the class in your AppServiceProvider
:
use Gtmassey\LaravelAnalytics\Analytics; use App\Analytics\CustomAnalytics; public function boot() { $this->app->bind(Analytics::class, CustomAnalytics::class); }
Now you can use the custom filter in your query:
use App\Analytics\CustomAnalytics; use Gtmassey\LaravelAnalytics\Period; use Gtmassey\LaravelAnalytics\Request\Dimensions; use Gtmassey\LaravelAnalytics\Request\Metrics; $report = CustomAnalytics::query() ->setMetrics(fn(Metrics $metrics) => $metrics->sessions()) ->setDimensions(fn(Dimensions $dimensions) => $dimensions->browser()) ->forPeriod(Period::defaultPeriod()) ->onlySessionsAbove(100) ->run();
Change log
Read CHANGELOG.md
Testing
To run tests, run:
composer test
Note that this command also runs code coverage analysis.
Contributing
Check out the contributing guide
Security
If you discover any security related issues, please email contact@garrettmassey.net instead of using the issue tracker.
Credits
Special thanks to Plytas for their early and significant contributions to the project. Without their help setting things up and their willingness to teach me new tools and techniques, this project would be dead in its tracks.
And a huge thanks to the team over at Spatie for their continued contributions to the open source community! Some of their work is used in this project, and I have used their packages as a foundation for projects for years.
License
MIT. Please see the license file for more information.