Laravel

Laravel Google Analytics Api Tutorial

January 31, 2018

author:

Laravel Google Analytics Api Tutorial

Google Analytics is considered one of the best tools for webmasters. It is utilized to generate high-end advanced reports of the websites. But, if you’ve worked with Google APIs earlier, you surely know how overwhelming it fills to digest all the information and setup correctly on the first go. For beginners, it may take days and days of stack overflowing and scratching their head to finally see the data flowing in Google Analytics dashboard.

One of the best parts of Laravel is community support. A wide range of options and packages are available to crack any problem. Just like it has a very easy solution to integrating Laravel Application with Google Analytics. In this section, we will use a third-party package for this purpose. So let us not waste any time and get started.

# Laravel-Analytics Package Setup

In your laravel project, install this package:

composer require spatie/laravel-analytics

Since Laravel 5.5+ auto registers service providers and facades, you don’t need to add them manually, but for older versions:

Add Service Provider in config/app.php:

# config/app.php

'providers' => [
    ...
    Spatie\Analytics\AnalyticsServiceProvider::class,
];

Also, add facade alias:

# config/app.php

'aliases' => [
    ...
    'Analytics' => Spatie\Analytics\AnalyticsFacade::class,
];

Next, publish the config file which will be created in config/analytics.php

php artisan vendor:publish --provider="Spatie\Analytics\AnalyticsServiceProvider"
# config/analytics.php

return [

    /*
     * The view id of which you want to display data.
     */
    'view_id' => env('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.
     */
    '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',
    ],
];

# Google API Setup

It’s now time to get required credentials from Google Developers Console to use its API. If you haven’t already, create a Google account, sign in and follow the below steps to enable API:

• Go ahead and create a new project if you don’t have any.

• We need a service account. Within IAM & Admin tab on the left sidebar, select Service Accounts or create service account directly.
Integrate Google Analytics Real time Users In Laravel Application, Create Service Account

• Next, select a relevant project to create a service account. Fill in the details and make sure to select JSON as your key type. Click on Create button.
Integrate Google Analytics Real time Users In Laravel Application, FIll Service Account Details

• Once, the private key is generated and downloaded the JSON file and place it within Project/storage/app/analytic/ namespace of your Laravel application.

Integrate Google Analytics Real time Users In Laravel Application, Store JSON Private Key in Laravel

# Laravel Google Analytics Dashboard

It is but obvious that we need Google Analytics Account in order to integrate into Laravel. In this section we will add certain permissions and from the dashboard and copy the View ID in our config file:

• You can create an account Google Analytics Account if you don’t have one. Add relevant information like Website Name, URL, etc.

Integrate Google Analytics Real time Users In Laravel Application, Create Google Analytics Account

• Within Admin tab, select relevant Account, Property, and View. And then choose User Management.

Integrate Google Analytics Real time Users In Laravel Application, Google Analytics User Management

• You may create a new user (if you want) and in Add Email Addresses field, add the client_email key from the downloaded JSON file:

Integrate Google Analytics Real time Users In Laravel Application, Google Analytics Map Service Account

• Next, go to dashboard and select View Settings.
Integrate Google Analytics Real time Users In Laravel Application, Google Analytics View Settings

• Finally, copy the View ID.
Integrate Google Analytics Real time Users In Laravel Application, Google Analytics Get View ID

• In the .env file of your Laravel Application, paste the View ID

# .env
...
ANALYTICS_VIEW_ID=154213098

# Laravel-Analytics Package Usage

Once installation finishes and everything is setup correctly, we can start using this package in our Laravel project. This package provides a range of methods to fetch analytics data just like Google Analytics API. A few of the popular ones are listed below:

//Retrieve Most Visited Pages
$pages = Analytics::fetchMostVisitedPages(Period::days(1));

//retrieve visitors and pageview data for the current day and the last fifteen days
$visitors = Analytics::fetchVisitorsAndPageViews(Period::days(15));

// Retrieve Total Visitors and Page Views
$total_visitors = Analytics::fetchTotalVisitorsAndPageViews(Period::days(7));

// Retrieve Top Referrers
$top_referrers = Analytics::fetchTopReferrers(Period::days(7));

// Retrieve User Types
$user_types = Analytics::fetchUserTypes(Period::days(7));

//Retrieve Top Browsers
$top_browser = Analytics::fetchTopBrowsers(Period::days(7));

//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'
      ]
);

Conclusion:
Since this may be overwhelming who just got started with Analytics in Laravel, we will close this post here. In the next post, we will work further from here and fetch real-time users from Google Analytics and bind them in our application. Hope to see you there!

Questions & Comments:

Thank you for reading. If you suggestions and questions, share them in the comment section below.

Leave a comment

Your email address will not be published. Required fields are marked *