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 '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
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.
• 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.
• Once, the private key is generated and downloaded the JSON file and place it within
Project/storage/app/analytic/ namespace of your Laravel application.
# 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.
• Within Admin tab, select relevant Account, Property, and View. And then choose 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:
• Next, go to dashboard and select View Settings.
• Finally, copy the 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' ] );
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.