Laravel Idea for PhpStorm - Full-featured IDE for productive artisans!

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

Published on by

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

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 Spatie.be 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:

composer require spatie/laravel-analytics

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

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

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

'aliases' => [
'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:

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

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

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
]
]
}

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:

<?php
 
namespace App\Services;
 
use Analytics;
use Spatie\Analytics\Period;
 
class Trending
{
public function week($limit = 15)
{
return $this->getResults(7);
}
 
protected function getResults($days, $limit=15)
{
return Analytics::fetchMostVisitedPages(Period::days($days), $limit);
}
}

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

$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:

protected function parseResults($data)
{
return $data->reject(function($item){
return $item['url'] == '/' or
$item['url'] == '/blog' or
starts_with($item['url'], '/category');
})->unique('url')->transform(function($item){
$item['pageTitle'] = str_replace(' - Laravel News', '', $item['pageTitle']);
return $item;
});
}

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:

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

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

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

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:

protected function getResults($days, $limit=15)
{
$data = Analytics::fetchMostVisitedPages(Period::days($days), $limit + 10);
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:

protected function parseResults($data, $limit)
{
return $data->reject(function($item){
return $item['url'] == '/' or
$item['url'] == '/blog' or
starts_with($item['url'], '/category');
})->unique('url')->transform(function($item){
$item['pageTitle'] = str_replace(' - Laravel News', '', $item['pageTitle']);
return $item;
})->splice(0, $limit);
}

This now gives the proper results:

Collection {#353 ▼
#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:

<?php
 
namespace App\Http\ViewComposers;
 
use App\Services\Trending;
use Illuminate\View\View;
 
class PopularityComposer
{
private $trending;
 
public function __construct(Trending $trending)
{
$this->trending = $trending;
}
 
public function compose(View $view)
{
$view->with('popular', $this->trending->week());
}
}

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:

view()->composer(
'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:

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

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.

Eric L. Barnes photo

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

Cube

Laravel Newsletter

Join 40k+ other developers and never miss out on new tips, tutorials, and more.

Laravel Forge logo

Laravel Forge

Easily create and manage your servers and deploy your Laravel applications in seconds.

Laravel Forge
Tinkerwell logo

Tinkerwell

The must-have code runner for Laravel developers. Tinker with AI, autocompletion and instant feedback on local and production environments.

Tinkerwell
No Compromises logo

No Compromises

Joel and Aaron, the two seasoned devs from the No Compromises podcast, are now available to hire for your Laravel project. ⬧ Flat rate of $7500/mo. ⬧ No lengthy sales process. ⬧ No contracts. ⬧ 100% money back guarantee.

No Compromises
Kirschbaum logo

Kirschbaum

Providing innovation and stability to ensure your web application succeeds.

Kirschbaum
Shift logo

Shift

Running an old Laravel version? Instant, automated Laravel upgrades and code modernization to keep your applications fresh.

Shift
Bacancy logo

Bacancy

Supercharge your project with a seasoned Laravel developer with 4-6 years of experience for just $2500/month. Get 160 hours of dedicated expertise & a risk-free 15-day trial. Schedule a call now!

Bacancy
Lucky Media logo

Lucky Media

Get Lucky Now - the ideal choice for Laravel Development, with over a decade of experience!

Lucky Media
Lunar: Laravel E-Commerce logo

Lunar: Laravel E-Commerce

E-Commerce for Laravel. An open-source package that brings the power of modern headless e-commerce functionality to Laravel.

Lunar: Laravel E-Commerce
LaraJobs logo

LaraJobs

The official Laravel job board

LaraJobs
SaaSykit: Laravel SaaS Starter Kit logo

SaaSykit: Laravel SaaS Starter Kit

SaaSykit is a Multi-tenant Laravel SaaS Starter Kit that comes with all features required to run a modern SaaS. Payments, Beautiful Checkout, Admin Panel, User dashboard, Auth, Ready Components, Stats, Blog, Docs and more.

SaaSykit: Laravel SaaS Starter Kit
Supercharge Your SaaS Development with FilamentFlow: The Ultimate Laravel Filament Boilerplate logo

Supercharge Your SaaS Development with FilamentFlow: The Ultimate Laravel Filament Boilerplate

Build your SaaS application in hours. Out-of-the-box multi-tenancy and seamless Stripe integration. Supports subscriptions and one-time purchases, allowing you to focus on building and creating without repetitive setup tasks.

Supercharge Your SaaS Development with FilamentFlow: The Ultimate Laravel Filament Boilerplate
Rector logo

Rector

Your partner for seamless Laravel upgrades, cutting costs, and accelerating innovation for successful companies

Rector
MongoDB logo

MongoDB

Enhance your PHP applications with the powerful integration of MongoDB and Laravel, empowering developers to build applications with ease and efficiency. Support transactional, search, analytics and mobile use cases while using the familiar Eloquent APIs. Discover how MongoDB's flexible, modern database can transform your Laravel applications.

MongoDB

The latest

View all →
Asymmetric Property Visibility in PHP 8.4 image

Asymmetric Property Visibility in PHP 8.4

Read article
Access Laravel Pulse Data as a JSON API image

Access Laravel Pulse Data as a JSON API

Read article
Laravel Forge adds Statamic Integration image

Laravel Forge adds Statamic Integration

Read article
Transform Data into Type-safe DTOs with this PHP Package image

Transform Data into Type-safe DTOs with this PHP Package

Read article
PHPxWorld - The resurgence of PHP meet-ups with Chris Morrell image

PHPxWorld - The resurgence of PHP meet-ups with Chris Morrell

Read article
Herd Executable Support and Pest 3 Mutation Testing in PhpStorm 2024.3 image

Herd Executable Support and Pest 3 Mutation Testing in PhpStorm 2024.3

Read article