Laravel Analytics v2
Laravel Packages / updated: August 08, 2016

Laravel Analytics v2

Freek Van der Herten and Spatie.be recently released a new version of their popular Google Analytics package.

Since the first release of this package Google has changed the preferred way of authenticating for API usage and this new version accounts for that as well as cleaned up a lot of the code and made it only available for PHP 7.0+

The Google authentication is a pain and the readme does a great job of showing you the exact steps to take. Following along I was able to complete the setup without pulling out all my hair.

After the authentication is set working with the package is really nice. As an example, I wanted to see if I could generate a list of trending pages here on Laravel News for the past month. Here is all I needed to do:

$analytics->fetchMostVisitedPages(
    Period::create(Carbon::now()->subMonth(), Carbon::now())
);

That returns a Laravel Collection with a “url” and “pageViews” attribute:

Collection {#364 ▼
  #items: array:20 [▼
    0 => array:2 [▼
      "url" => "/"
      "pageViews" => 126600
    ]
    1 => array:2 [▼
      "url" => "/2016/06/look-whats-coming-laravel-5-3/"
      "pageViews" => 126599
    ]
    2 => array:2 [▼
      "url" => "/2016/06/laravel-and-elasticsearch/"
      "pageViews" => 126598
    ]

Of course, it includes other useful methods for the most common stats you will need:

  • fetchVisitorsAndPageViews()
  • fetchTopReferrers()
  • fetchTopBrowsers()
  • performQuery() – Advanced option to perform any query you need.

If you are needing to integrate with Google Analytics check out this package. Even you are not the market for analytics but still need to use Google API bookmark it as a guide for setting up API accounts.

Laravel News Partners

Newsletter

Join the weekly newsletter and never miss out on new tips, tutorials, and more.