In this post, I will explain how to retrieve data from Google Analytics. In this tutorial we will use laravel-analytics package by Spatie. So, let’s get started by installing the package.
Step 1: Install Package
The most easiest way to install package is using composer
. To install this, simply run the below command:
composer require spatie/laravel-analytics
In Laravel 5.5 and above, you don’t need to register the service provider but, below Laravel 5.5 version, you need to register service provider in config/app.php
'providers' => [ ........ Spatie\Analytics\AnalyticsServiceProvider::class, ];
Similarly, add Facade
in alias
section.
'aliases' => [ ......... 'Analytics' => Spatie\Analytics\AnalyticsFacade::class, ];
To configure your configuration for this package, you can publish this package. You can publish using below command:
php artisan vendor:publish --provider="Spatie\Analytics\AnalyticsServiceProvider"
This will publish a configuration file. Sample of the configuration file looks like below:
return [ /* * The view id of which you want to display data. */ 'view_id' => env('GOOGLE_ANALYTICS_VIEW_ID'), /* * Path to the client secret json file. Take a look at the README of this package * to learn how to get this file. You can also pass the credentials as an array * instead of a file path. */ 'service_account_credentials_json' => storage_path('app/analytics/service-account-credentials.json'), /* * The amount of minutes the Google API responses will be cached. * If you set this to zero, the responses won't be cached at all. */ 'cache_lifetime_in_minutes' => 60 * 24, /* * Here you may configure the "store" that the underlying Google_Client will * use to store it's data. You may also add extra parameters that will * be passed on setCacheConfig (see docs for google-api-php-client). * * Optional parameters: "lifetime", "prefix" */ 'cache' => [ 'store' => 'file', ], ];
Add view_id
in your .env
file
GOOGLE_ANALYTICS_VIEW_ID=you_view_id
Step 2: Obtain Google Analytics Credentials
Getting API Credentials
We will need Google API’s credentials to fetch our data. You can get clear documentation at it’s github repo, but I will explain step by step.
Go the Google’s API page and select your project. If you haven’t create any, create a new one.
Now, click on “Enable APIs and Services”.
Search for “Google Analytics Reporting API”
Create a “Service account key”. This will download a json
file. Please save it safely.
Now, create a folder named analytics
inside app
directory and put the recently downloaded json
file inside this folder. Please note that, this file contain sensitive data.
Granting permissions to your Analytics
Go to this Google Suite and create a new account.
The last thing you’ll have to do is fill in the view_id in the config file. You can get the right value on the Analytics site. Go to “View setting” in the Admin-section of the property.
Grab the view id and paste it inside your config/analytics.php
in view_id
section or define in .env
file and access from here.
/* * The view id of which you want to display data. */ 'view_id' => env('GOOGLE_ANALYTICS_VIEW_ID'),
Great! we have successfully integrated the package in our application. It’s time to implement the package. Basic example of it’s usage is given below:
//retrieve visitors and pageview data for the current day and the last seven days $analyticsData = Analytics::fetchVisitorsAndPageViews(Period::days(7)); //retrieve visitors and pageviews since the 6 months ago $analyticsData = Analytics::fetchVisitorsAndPageViews(Period::months(6)); //retrieve sessions and pageviews with yearMonth dimension since 1 year ago $analyticsData = Analytics::performQuery( Period::years(1), 'ga:sessions', [ 'metrics' => 'ga:sessions, ga:pageviews', 'dimensions' => 'ga:yearMonth' ] );
Note: Please note that, every method will return a Illuminate\Support\Collection
instance.
Step 3: Usage
Let’s grab some popular post.
$popular = Analytics::fetchMostVisitedPages(Period::days(7), 5); dd($popular);
This will retrieve most popular blog post are return a collection.
Collection {#400 ▼ #items: array:17 [▼ 0 => array:3 [▼ "url" => "/" "pageTitle" => "Laravel News" "pageViews" => 10 ] 1 => array:3 [▼ "url" => "/" "pageTitle" => "Laravel News - News and information about Laravel" "pageViews" => 9 ] 2 => array:3 [▼ "url" => "/2016/06/look-whats-coming-laravel-5-3/" "pageTitle" => "A look at what’s coming to Laravel 5.3" "pageViews" => 8 ] 3 => array:3 [▼ "url" => "/2016/06/look-whats-coming-laravel-5-3/" "pageTitle" => "A look at what's coming to Laravel 5.3 - Laravel News" "pageViews" => 7 ] 4 => array:3 [▼ "url" => "/2016/08/laravel-5-3-rc1-is-now-released/" "pageTitle" => "Laravel 5.3 RC1 is now released" "pageViews" => 6 ] ] }
Note: Please don’t forget to include use Analytics;
and use Spatie\Analytics\Period;
Modifying Time limit
You can pass startDate
and endDate
to period object.
$startDate = Carbon::now()->subYear(); $endDate = Carbon::now(); Period::create($startDate, $endDate);
Available Methods
Visitors and pageviews
public function fetchVisitorsAndPageViews(Period $period): Collection
The function returns a Collection in which each item is an array that holds keys date, visitors, pageTitle and pageViews.
Total visitors and pageviews
public function fetchTotalVisitorsAndPageViews(Period $period): Collection
The function returns a Collection in which each item is an array that holds keys date, visitors, and pageViews.
Most visited pages
public function fetchMostVisitedPages(Period $period, int $maxResults = 20): Collection
The function returns a Collection in which each item is an array that holds keys url, pageTitle and pageViews.
Top referrers
public function fetchTopReferrers(Period $period, int $maxResults = 20): Collection
The function returns a Collection in which each item is an array that holds keys url and pageViews.
User Types
public function fetchUserTypes(Period $period): Collection
The function returns a Collection in which each item is an array that holds keys type and sessions.
Top browsers
public function fetchTopBrowsers(Period $period, int $maxResults = 10): Collection
The function returns a Collection in which each item is an array that holds keys browser and sessions.
All other Google Analytics queries
To perform all other queries on the Google Analytics resource use performQuery. Google’s Core Reporting API provides more information on which metrics and dimensions might be used.
public function performQuery(Period $period, string $metrics, array $others = [])
You can get access to the underlying Google_Service_Analytics object:
Analytics::getAnalyticsService();
Hope you got ideas about installing this package and available methods. Enjoy!