To use this site please enable javascript on your browser! How ChartJs Can Display Laravel 5 Analytics Data

We use cookies, as well as those from third parties, for sessions in order to make the navigation of our website easy and safe for our users. We also use cookies to obtain statistical data about the navigation of the users.

See Terms & Conditions

How ChartJs Can Display Laravel 5 Analytics Data

by Bryce Andy 04:11 Nov 14 '18

ChartJS Cover

So you have a working Laravel project, but you needed to see the number of visitors you have or from which countries are your visitors from or which page is viewed more by the people from your country? All displayed in beautiful animated graphs?

If your answer was YES to any of those questions then you are a few steps away... 

This is gunna be fun gif

Fetching Google Analytics Data

I assume many of us might have already setup Google Analytics and can retrieve their website data, so you can skip this step. But if you have just started and haven't fetched your site's data just follow along. 

First we install a package using composer, that will help with integrating with Google Analytics.

composer require spatie/laravel-analytics

To let Laravel be aware of your new service provider, go to your config/app.php and add it to the providers and aliases like this

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

'aliases' => [
   //...
    'Analytics' => Spatie\Analytics\AnalyticsFacade::class,
];

Then you will have to publish the configurations using the artisan command

php artisan vendor:publish --provider="Spatie\Analytics\AnalyticsServiceProvider"

If all was done correctly, you should see a new file config/analytics.php that looks like this

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. 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',
    ],
];

We will see how to obtain the ANALYTICS_VIEW_ID and service-account-credentials.json file, but notice the pair that stores the json file, storage_path indicates in the root directory of your project inside the storage directory, you should have a app/analytics directory to store your service-account-credentials.json file.

Someone else might use another option by editing it to be  'service_account_credentials_json' => app_path('secret/service-account-credentials.json'),  meaning app_path is the directory app in the root folder, and inside it is a secret directory where the file service-account-credentials.json will reside.

Both these storage locations are not advisable because this json file contains data that shouldn't be seen by anyone else, so for this case the json file should be stored securely.

How to get the json file and Analytics View Id from Google

To obtain them, we are to request Google some credentials to use their API. Create a Google account, login and visit the API console. Click Select Project on the right, then go ahead and search the Analytics API in the search box.

After selecting the API, on the blue button on top click Enable. Now on the left sidebar click Credentials and under the create credentials, select Service Account Key. Fill in the details given and select JSON then click create.

You will have now downloaded the json file we needed, next is renaming it and storing as we discussed above. To get the View Id, create an analytics account for your website, then go to the Admin section and click User Management.

Google Analytics Dashboard

Hereafter we can add permissions for your Google API project to use the analytics. Simply copy the email you see in the json file you downloaded and assign permissions. Otherwise Google Analytics and your Google API wont exchange your analytics.

Also make sure to click Tracking Info, select Tracking Code and copy the code given then paste on the pages you want to track .

Finally, above the User Management click View Settings. Copy the view ID and put it in your env variable ANALYTICS_VIEW_ID

Querying Data for ChartJs

Now the second part things get more interesting. To find data to be used by ChartJs we will create a PHP class in the app/Libraries directory, we will name it GoogleAnalytics.php

<?php 
namespace App\Libraries;

use Analytics;
use Spatie\Analytics\Period;

class GoogleAnalytics{

    static function topCountries() {
        $country = Analytics::performQuery(Period::days(30),'ga:sessions',  ['dimensions'=>'ga:country','sort'=>'-ga:sessions']);
        $result= collect($country['rows'] ?? [])->map(function (array $dateRow) {
            return [
                'country' =>  $dateRow[0],
                'sessions' => (int) $dateRow[1],
            ];
        });
        
        return $result;
    }

    static function topBrowsers()
    {
        //
    }

}

For our example we will query the top countries that visit our site. If you want to see many other query ideas see here.

In the root directory, edit your composer.json like this

"autoload": {
      "classmap": [
        "database"
      ],
      "psr-4": {
        "App\\": "app/",
        "Library\\": "app/library/"
      }
    },

then run the following command to update the autoload content

composer dump auto-load

Create a controller for you dashboard or analytics logic with the artisan command

php artisan make:controller AnalyticsController

Make changes to the controller and make sure it looks something like this

<?php

namespace App\Http\Controllers;

use Analytics;
use Spatie\Analytics\Period;
use App\Libraries\GoogleAnalytics;

class AnalyticsController extends Controller
{
    public function index()
    {
        $result = GoogleAnalytics::topCountries();
        $country = $result->pluck('country');
        $country_sessions = $result->pluck('sessions');

        
        return view('dashboard', compact('country', 'country_sessions'));
    }
}

Important things to note, in our web.php file, the route that links to the dashboard must be connected to the index method above i.e

Route::get('dashboard', 'AnalyticsController@index');

and we must have a dashboard.blade.php file in our resources/view.

Displaying the Chart

The difficult parts are completed, now we head over our view to first include the ChartJs CDN and create a canvas for our graph.

<!-- Inside the head tag -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.4.0/Chart.min.js"></script>

<!-- Inside the body tag -->
<canvas id="myChart" style="height:auto; width: auto; min-height:250px" aria-label="Analytics Chart" role="img"></canvas>

After this we can now use javascript/jquery to display the chart inside the canvas

<!-- Before the body closing tag -->
<script>

        function getRandomColor() {
            var letters = '0123456789ABCDEF'.split('');
            var color = '#';
            for (var i = 0; i < 6; i++) {
                color += letters[Math.floor(Math.random() * 16)];
            }
            return color;
        }

        function getRandomColorEach(count) {
            var data =[];
            for (var i = 0; i < count; i++) {
                data.push(getRandomColor());
            }
            return data;
        }

        var countries = {!! json_encode($country) !!};

        var ctx = document.getElementById('myChart').getContext('2d');
        var chart = new Chart(ctx, {
            // The type of chart we want to create
            type: 'doughnut',

            // The data for our dataset
            data: {
                labels: {!! json_encode($country) !!},
                datasets: [{
                    label: "Countries",
                    backgroundColor: getRandomColorEach(countries.length),
                    borderColor: '#328daa',
                    data: {!! json_encode($country_sessions) !!},
                }]
            },

            // Configuration options go here
            options: {
                responsive: true
            }
        });
</script>

Explanation of the code:

The functions getRandomColor and getRandomColorEach are used collectively to display different colors for the background property.

This is important because we chose a doughnut chart and each country will need its own color, thus the for loop comes in handy.

All data we are mapping whether it came as a collection or array it has to be changed to json in order for ChartJs to use it.

There are a variety of charts in the documentation that you can use, but here is the result of our example.

ChartJS Result Cover

Happy Coding!

Updated 04:05 May 12 '21

If you like this content, please consider buying me coffee.
Thank you for your support!

Become a Patron!