How to Create A Most Popular List with Laravel and Google Analytics


September 1st, 2016

How to Create A Most Popular List with Laravel and Google Analytics

Here on Laravel News, I wanted to generate a list of the most popular posts for the past seven days and display the results from most popular to least popular.

To solve this problem I thought of two solutions. The first is to build my own tracking system so I could keep a count and then use it for ordering. However, that could generate a huge amount of data and it seemed like a solution that an analytics tracking service could handle.

As I was fumbling through the Google Analytics API I found a Laravel Analytics package by that allows you to easily retrieve data from your Google Analytics account and it seemed like the best way to solve this problem. Let’s look at how I used it to generate a list of popular posts here on Laravel News.

Installation and Setup

The installation is typical for any Laravel package, you first install the package through composer:

1composer require spatie/laravel-analytics

Next, add the service provider to config/app.php

1'providers' => [
2 Spatie\Analytics\AnalyticsServiceProvider::class,

Finally, add the Facade to the same config/app.php

1'aliases' => [
2 'Analytics' => Spatie\Analytics\AnalyticsFacade::class,

Once that is setup the hardest part of the process begins and it’s no fault to the package. It’s just that Google has a crazy system in place for generating credentials. It will be best to visit this section of the readme as it steps through how to set this up complete with screenshots.

Fetching the most popular

The Analytics package makes fetching the data simple and here is an example for grabbing the most popular pages over the past seven days with a limit set:

1$pages = Analytics::fetchMostVisitedPages(Period::days(7), $limit);

Then it returns a Laravel Collection of the results that look something like this:

1Collection {#400 ▼
2 #items: array:17 [▼
3 0 => array:3 [▼
4 "url" => "/"
5 "pageTitle" => "Laravel News"
6 "pageViews" => 10
7 ]
8 1 => array:3 [▼
9 "url" => "/"
10 "pageTitle" => "Laravel News - News and information about Laravel"
11 "pageViews" => 9
12 ]
13 2 => array:3 [▼
14 "url" => "/2016/06/look-whats-coming-laravel-5-3/"
15 "pageTitle" => "A look at what’s coming to Laravel 5.3"
16 "pageViews" => 8
17 ]
18 3 => array:3 [▼
19 "url" => "/2016/06/look-whats-coming-laravel-5-3/"
20 "pageTitle" => "A look at what's coming to Laravel 5.3 - Laravel News"
21 "pageViews" => 7
22 ]
23 4 => array:3 [▼
24 "url" => "/2016/08/laravel-5-3-rc1-is-now-released/"
25 "pageTitle" => "Laravel 5.3 RC1 is now released"
26 "pageViews" => 6
27 ]
28 ]

If you notice the top two results are of the home page, then the second two are of the same post, and the reason these show twice is because the titles are different. One set is from before I changed the titles on the site and one set after.

Another issue is that I don’t want the home page to be in the list at all. I’d prefer this to be limited to posts only.

Let’s work through cleaning these up as we complete the integration.

Building A Wrapper Class

Now that I am getting results and I know I’m going to need to parse them I decided to create a class that will handle the fetching and the processing.

I created a new file named app/Services/Trending.php and stubbed it out with the basic fetching code:

3namespace App\Services;
5use Analytics;
6use Spatie\Analytics\Period;
8class Trending
10 public function week($limit = 15)
11 {
12 return $this->getResults(7);
13 }
15 protected function getResults($days, $limit=15)
16 {
17 return Analytics::fetchMostVisitedPages(Period::days($days), $limit);
18 }

Now calling this should give us the same results as before and here is an example call:

1$trending = app('App\Services\Trending')->week();

Next, it needs another method to parse the results. As mentioned earlier it needs to remove any duplicates, remove any pages that are not actual posts, and also remove the “ – Laravel News” suffix on titles that Google is reporting on.

Because the results from the fetchMostVisitedPages is a Collection this allows us to easily utilize all its methods and here is the finished method:

1protected function parseResults($data)
3 return $data->reject(function($item){
4 return $item['url'] == '/' or
5 $item['url'] == '/blog' or
6 starts_with($item['url'], '/category');
7 })->unique('url')->transform(function($item){
8 $item['pageTitle'] = str_replace(' - Laravel News', '', $item['pageTitle']);
9 return $item;
10 });

If we step through this it first rejects any items with the url of “/“, or “/blog”, or if the url starts with “/category”. These are my three primary sections that generate enough traffic where they would show in the list.

Next, it calls, ->unique('url') to prevent any duplicate url’s from passing through.

Finally, a ->transform() call to strip the “ – Laravel News” suffix.

Next, modify the getResults so it uses the parser:

1protected function getResults($days, $limit=15)
3 $data = Analytics::fetchMostVisitedPages(Period::days($days), $limit);
4 return $this->parseResults($data);

Now if we run it again all the returned data should be correct:

1Collection {#396 ▼
2 #items: array:11 [▼
3 2 => array:3 [▼
4 "url" => "/2016/06/look-whats-coming-laravel-5-3/"
5 "pageTitle" => "A look at what’s coming to Laravel 5.3"
6 "pageViews" => 10
7 ]
8 4 => array:3 [▼
9 "url" => "/2016/08/laravel-5-3-rc1-is-now-released/"
10 "pageTitle" => "Laravel 5.3 RC1 is now released"
11 "pageViews" => 9
12 ]
13 5 => array:3 [▼
14 "url" => "/2016/07/laravel-5-3-recap/"
15 "pageTitle" => "Laracon: Laravel 5.3 Recap"
16 "pageViews" => 8
17 ]
18 6 => array:3 [▶]
19 7 => array:3 [▶]
20 8 => array:3 [▶]
21 9 => array:3 [▶]
22 12 => array:3 [▶]
23 13 => array:3 [▶]
24 14 => array:3 [▶]
25 15 => array:3 [▶]
26 ]

It appears to be working, but notice that instead of the desired 15 items, these results only have 11. That’s because we are originally fetching the 15 top items, then rejected any duplicates. That causes us to get less than the fifteen we wanted.

The solution I came up with is to request more than I’m going to need and then splice off the number we really want. First, change getResults to grab more than needed:

1protected function getResults($days, $limit=15)
3 $data = Analytics::fetchMostVisitedPages(Period::days($days), $limit + 10);
4 return $this->parseResults($data, $limit);

Notice that instead of calling fetchMostVisitedPages with the limit passed it’s now adding ten to it. That way we have a buffer of extras.

Next modify the parseResults to splice off the limit at the end of all the parsing:

1protected function parseResults($data, $limit)
3 return $data->reject(function($item){
4 return $item['url'] == '/' or
5 $item['url'] == '/blog' or
6 starts_with($item['url'], '/category');
7 })->unique('url')->transform(function($item){
8 $item['pageTitle'] = str_replace(' - Laravel News', '', $item['pageTitle']);
9 return $item;
10 })->splice(0, $limit);

This now gives the proper results:

1Collection {#353 ▼
2 #items: array:15 [▶]

With that all working it’s time to implement it into the view and I believe this would make a great candidate for a view composer.

Creating the View Composer

If you are not familiar with View Composers here is how the documentation describes them:

View composers are callbacks or class methods that are called when a view is rendered. If you have data that you want to be bound to a view each time that view is rendered, a view composer can help you organize that logic into a single location.

Because this data is only going to show in the sidebar and it could be called from any controller it’s a prime candidate for a view composer.

To setup this View Composer create app/Http/ViewComposers/PopularityComposer.php and add the following class:

3namespace App\Http\ViewComposers;
5use App\Services\Trending;
6use Illuminate\View\View;
8class PopularityComposer
10 private $trending;
12 public function __construct(Trending $trending)
13 {
14 $this->trending = $trending;
15 }
17 public function compose(View $view)
18 {
19 $view->with('popular', $this->trending->week());
20 }

This is setting up our previous Trending class as a dependency and then in the compose method adding a view variable named “popular” that will hold our Collection of results.

Next, open app/Providers/ComposerServiceProvider.php and register our new composer:

2 'sidebar', PopularityComposer::class

This is registering the PopularityComposer class that we just created to the sidebar view.

Adding the list to the view

The final part is adding the actual list to the sidebar. Create resources/views/sidebar.blade.php and add a simple list like this:

2 @foreach ($popular as $post)
3 <li><a href="{{ $post['url'] }}">{{ $post['pageTitle'] }}</a></li>
4 @endforeach

That’s it. You should now see a nice trending list of your posts in a list.

Wrap Up

As you can see from this short tutorial utilizing by utilizing a community package, Laravel Collections, and View Composers I was able to quickly and easily setup a most popular list.

Filed in:

Eric L. Barnes

Eric is the creator of Laravel News and has been covering Laravel since 2012.