Home Laravel Most popular posts with Laravel and Google Analytics

Most popular posts with Laravel and Google Analytics

popular posts with laravel and google analytics

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.
google analytics create project

Now, click on “Enable APIs and Services”.
enable google api

Search for “Google Analytics Reporting API”
Google Analytics API

Create a “Service account key”. This will download a json file. Please save it safely.
generate service amount key

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.
generate service amount key_002

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.
google view id

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!

27 COMMENTS

  1. Its such as you learn my mind! You appear to grasp a lot approximately this, such as you wrote the
    e-book in it or something. I believe that you simply can do with a few percent to pressure the message
    house a little bit, but other than that, this is magnificent blog.
    A great read. I’ll certainly be back.

  2. A person essentially lend a hand to make significantly articles
    I might state. That is the first tine I frequented your web pag and up to now?
    I amazed with the analsis you made to create
    this particular publish extraordinary. Fantastic process!

  3. My coder is trying to persuade me to move to .net from PHP.
    I have always disliked the idea because of the costs.
    But he’s tryiong none the less. I’ve been using Movable-type on several websites
    for about a year and am nervous about switching to another platform.
    I have heard good things about blogengine.net.
    Is there a way I can import all my wordpress content into it?
    Any help would be really appreciated!

  4. I’ve been exploring for a bit for any high-quality articles
    or weblog posts in this sort of space . Exploring in Yahoo I at last stumbled
    upon this web site. Studying this info So i’m satisfied to
    exhibit that I have a very just right uncanny feeling I found out
    exactly what I needed. I most indisputably will make sure to do not disregard this site and give it a look
    on a continuing basis.

  5. Hello, i read your blog occasionally and i own a similar
    one and i was just wondering if you get a lot of spam feedback?

    If so how do you stop it, any plugin or anything you can recommend?
    I get so much lately it’s driving me crazy so any assistance is
    very much appreciated.

  6. I’m really loving the theme/design of your blog. Do you ever run into any browser compatibility issues?
    A few of my blog audience have complained about my blog not working correctly in Explorer but
    looks great in Opera. Do you have any recommendations
    to help fix this issue?

  7. You really make it seem really easy together with your presentation however I in finding this matter to
    be really something that I feel I might by no means understand.
    It sort of feels too complicated and very huge
    for me. I am taking a look ahead in your next publish, I’ll try to get the grasp of it!

  8. It’s appropriate time to make some plans for the
    future and it is time to be happy. I have read this post
    and if I could I want to suggest you some interesting things or suggestions.
    Maybe you could write next articles referring to this article.

    I want to read more things about it!

  9. Whats up this is kinda of off topic but I was wondering if blogs use WYSIWYG editors or if you have
    to manually code with HTML. I’m starting a blog soon but have no coding know-how so I wanted to get guidance from someone with experience.
    Any help would be greatly appreciated!

  10. While you might be shopping for LEGOs for your
    D&D, someone happens to encounter such sets which are particularly attracting girls.
    Sometimes this will work out favourably and at in other cases,
    not so favourably. It is with this environment that Bing has sprouted, and many notice
    the search algorithms will be more centered on content than many with the other search engines like google.

LEAVE A REPLY

Please enter your comment!
Please enter your name here