How to Integrate Google Analytics with Laravel 8

How to Integrate Google Analytics with Laravel 8

Admin
Admin・ 20 Agustus 2021
15 min read ・ 16269 views

Laravel Analytics - Google Analytics is a free tool provided by Google, which functions to view or analyze website performance in search engines. The integration of the Analytics tool on the website is very important or you can say it is mandatory. Analytics tools that can be used can be Google Analytics or it can be something else.

In pupoluar CMS such as wordpress or blogger, we can easily integrate google analytics directly in the dashboard with the available plugins. Or on weebly also directly available analytics on the dashboard. But if our website does not use a CMS or for example our website is made with the Laravel PHP framework, how do we install or integrate it with google analytics? so that we can easily see or analyze website performance directly from our dashboard without opening a new tab google analytics? It's very easy, we can integrate google analytics in laravel with laravel analytics package from spatie.

So in this article, I will share a tutorial on how to integrate Google Analytics in Laravel with the Laravel Analytics package starting from scratch. But first, let's get acquainted with the laravel analytics package from spatie.

Laravel Analytics Package is a package created by spatie.be, a web agency based in Belgium. Spatie has made a lot of popular laravel packages such as laravel permissions, laravel activity log, laravel newsletter and many more. Laravel Analytics Package was created to make it easier to retrieve information such as pageviews, top referers and others from the Google Analytic API.

Register Google Analytics Account

Before going to the steps to integrate Laravel Analytics, let's register Google Analytics first by visiting the official website here.

google analytics

In this first step, please fill in your account name, followed by selecting the service option (checkbox) provided by Google. If so, continue by clicking Next.

google analytics

Continue by filling in the property details in the available input form. Then click Show advanced options.

google analytics

Here we will create a Universal Analytics property with the tracking code prefixed with UA-xxxxxxx. Then enter the URL of your site and click Next.

google analytics

In this step, please fill in your detailed business information then continue by clicking Create.

google analytic universal

Okay, we've managed to register google analytics. Next, please copy the Global Site Tag (gtag.js), paste it in your global view (in laravel it is usually placed in layouts.app).

Get view_id

google analytics

Later we need view_id which will be used for google analytics integration in laravel. We can get the view_id by going to the sidebar menu "Admin" then in the view settings or view settings. Save this view_id for later.

*sorry, in the step of registering a google analytic account I use Bahasa Indonesia

Register for Google Cloud Platform Account

To be able to use the API from google, we need to get the credentials that can be obtained on the Google Cloud Platform. Please register using the same email (google analytics) on the official Google API's site.

Google API

Click Create Project, then fill in the project name input form and click Create.

Google API

Then go to Credentials, click Create Credentials and select service account.

google API

Please fill in the service account details then click Create and Continue until there is a DONE button.

google api

Okay, we've managed to create a service account. Next we need to generate a key to be able to continue using or integrating google analytics in laravel. In the action please click manage keys.

google api

Create a new key by pressing the ADD KEY button then select the JSON type. After pressing the CREATE button, we have successfully downloaded a file of type JSON which contains the key details that we will use later. Rename the json file with service-account-credentials.json, then place it in the storage/app/analytics folder (if there is no analytics folder, please create a new folder).

google analytics API

Previously we need to enable Google Analytics API here. Activate by pressing the ENABLE button.

Granting Access Permission to Analytics Properties

grant permission google analytics

In the previous step we have got a json file that contains the keys that we will use later. Well now, we need to add user permissions on User Management View or User Management.

analytics api

Please fill in the email address with client_email obtained from the json file in the previous step. For permission, you can select read & analyze then click Add.

Start Coding

After in the first step we register google analytics, then we create a service account on the google cloud platform, get service account credentials in the form of a JSON file and have also given access permissions to be able to use the google analytics API in our laravel project, now it's time for us to code .

Install Laravel

composer create-project laravel/laravel laravel-analytics

Here I will install the latest laravel via composer with the name laravel-analytics.

Install Laravel Analytics Package

composer require spatie/laravel-analytics

After successfully installing laravel, in the terminal please enter the laravel project directory that was just created with the cd laravel-analytics. Then run the command as above to start installing the laravel analytics package in our laravel project.

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

 

Then we can publish the analytics config file in the laravel analytics package with the above command.

<?php

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

Now if we look at config/analytics.php, to be able to run or read google analytics information data with the API in laravel analytics package this requires a view_id that points to the .env file (ANALYTICS_VIEW_ID). For that, please add a new record in the .env file, namely ANALYTICS_VIEW_ID=your_view_id. Where do you get the view_id from? view_id we have already got in Get view_id (Table of Contents).

Then make sure the JSON file that has been successfully downloaded in the previous step on the Google Cloud Platform is copied to the storage/app/analytics folder. If there is no analytics folder in the storage/app folder, please create a new folder with that name. Then we can rename the JSON file that was successfully downloaded earlier with the name service-account-credentials.json.

Edit Route

<?php

use Illuminate\Support\Facades\Route;
use Spatie\Analytics\Period;

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

Route::get('/', function () {

    $analyticsData = Analytics::fetchVisitorsAndPageViews(Period::days(7));
    return view('welcome', ['analyticsData' => $analyticsData]);
}); 

We will try laravel analytics in routes/web.php by displaying Visitors and Page Views data and with the last 7 days period.

Edit welcome.blade.php

<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">

        <title>Laravel</title>

        <!-- Fonts -->
        <link href="https://fonts.googleapis.com/css2?family=Nunito:wght@400;600;700&display=swap" rel="stylesheet">

        <!-- Styles -->
        <style>
            /*! normalize.css v8.0.1 | MIT License | github.com/necolas/normalize.css */html{line-height:1.15;-webkit-text-size-adjust:100%}body{margin:0}a{background-color:transparent}[hidden]{display:none}html{font-family:system-ui,-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Helvetica Neue,Arial,Noto Sans,sans-serif,Apple Color Emoji,Segoe UI Emoji,Segoe UI Symbol,Noto Color Emoji;line-height:1.5}*,:after,:before{box-sizing:border-box;border:0 solid #e2e8f0}a{color:inherit;text-decoration:inherit}svg,video{display:block;vertical-align:middle}video{max-width:100%;height:auto}.bg-white{--bg-opacity:1;background-color:#fff;background-color:rgba(255,255,255,var(--bg-opacity))}.bg-gray-100{--bg-opacity:1;background-color:#f7fafc;background-color:rgba(247,250,252,var(--bg-opacity))}.border-gray-200{--border-opacity:1;border-color:#edf2f7;border-color:rgba(237,242,247,var(--border-opacity))}.border-t{border-top-width:1px}.flex{display:flex}.grid{display:grid}.hidden{display:none}.items-center{align-items:center}.justify-center{justify-content:center}.font-semibold{font-weight:600}.h-5{height:1.25rem}.h-8{height:2rem}.h-16{height:4rem}.text-sm{font-size:.875rem}.text-lg{font-size:1.125rem}.leading-7{line-height:1.75rem}.mx-auto{margin-left:auto;margin-right:auto}.ml-1{margin-left:.25rem}.mt-2{margin-top:.5rem}.mr-2{margin-right:.5rem}.ml-2{margin-left:.5rem}.mt-4{margin-top:1rem}.ml-4{margin-left:1rem}.mt-8{margin-top:2rem}.ml-12{margin-left:3rem}.-mt-px{margin-top:-1px}.max-w-6xl{max-width:72rem}.min-h-screen{min-height:100vh}.overflow-hidden{overflow:hidden}.p-6{padding:1.5rem}.py-4{padding-top:1rem;padding-bottom:1rem}.px-6{padding-left:1.5rem;padding-right:1.5rem}.pt-8{padding-top:2rem}.fixed{position:fixed}.relative{position:relative}.top-0{top:0}.right-0{right:0}.shadow{box-shadow:0 1px 3px 0 rgba(0,0,0,.1),0 1px 2px 0 rgba(0,0,0,.06)}.text-center{text-align:center}.text-gray-200{--text-opacity:1;color:#edf2f7;color:rgba(237,242,247,var(--text-opacity))}.text-gray-300{--text-opacity:1;color:#e2e8f0;color:rgba(226,232,240,var(--text-opacity))}.text-gray-400{--text-opacity:1;color:#cbd5e0;color:rgba(203,213,224,var(--text-opacity))}.text-gray-500{--text-opacity:1;color:#a0aec0;color:rgba(160,174,192,var(--text-opacity))}.text-gray-600{--text-opacity:1;color:#718096;color:rgba(113,128,150,var(--text-opacity))}.text-gray-700{--text-opacity:1;color:#4a5568;color:rgba(74,85,104,var(--text-opacity))}.text-gray-900{--text-opacity:1;color:#1a202c;color:rgba(26,32,44,var(--text-opacity))}.underline{text-decoration:underline}.antialiased{-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale}.w-5{width:1.25rem}.w-8{width:2rem}.w-auto{width:auto}.grid-cols-1{grid-template-columns:repeat(1,minmax(0,1fr))}@media (min-width:640px){.sm\:rounded-lg{border-radius:.5rem}.sm\:block{display:block}.sm\:items-center{align-items:center}.sm\:justify-start{justify-content:flex-start}.sm\:justify-between{justify-content:space-between}.sm\:h-20{height:5rem}.sm\:ml-0{margin-left:0}.sm\:px-6{padding-left:1.5rem;padding-right:1.5rem}.sm\:pt-0{padding-top:0}.sm\:text-left{text-align:left}.sm\:text-right{text-align:right}}@media (min-width:768px){.md\:border-t-0{border-top-width:0}.md\:border-l{border-left-width:1px}.md\:grid-cols-2{grid-template-columns:repeat(2,minmax(0,1fr))}}@media (min-width:1024px){.lg\:px-8{padding-left:2rem;padding-right:2rem}}@media (prefers-color-scheme:dark){.dark\:bg-gray-800{--bg-opacity:1;background-color:#2d3748;background-color:rgba(45,55,72,var(--bg-opacity))}.dark\:bg-gray-900{--bg-opacity:1;background-color:#1a202c;background-color:rgba(26,32,44,var(--bg-opacity))}.dark\:border-gray-700{--border-opacity:1;border-color:#4a5568;border-color:rgba(74,85,104,var(--border-opacity))}.dark\:text-white{--text-opacity:1;color:#fff;color:rgba(255,255,255,var(--text-opacity))}.dark\:text-gray-400{--text-opacity:1;color:#cbd5e0;color:rgba(203,213,224,var(--text-opacity))}}
        </style>

        <style>
            body {
                font-family: 'Nunito', sans-serif;
            }
        </style>
    </head>
    <body>
        <div class="relative flex items-top justify-center min-h-screen sm:items-center py-4 sm:pt-0">
            <table class="table-auto">
                <thead>
                  <tr>
                    <th>#</th>
                    <th>Date</th>
                    <th>Visitors</th>
                    <th>Page Title</th>
                    <th>Page Views</th>
                  </tr>
                </thead>
                <tbody>
                    @php
                        $no = 0;
                    @endphp
                  @foreach ($analyticsData as $data)
                  <tr>
                    <td>{{ ++$no }}</td>
                    <td>{{ $data['date'] }}</td>
                    <td>{{ $data['visitors'] }}</td>
                    <td>{{ $data['pageTitle'] }}</td>
                    <td>{{ $data['pageViews'] }}</td>
                  </tr>
                  @endforeach
                </tbody>
              </table>
        </div>
    </body>
</html> 

Then in the welcome.blade.php file, we change it to display a table of visitor information and page views from the laravel analytics package which retrieves real-time data from our google analytics account. And now for example, the code in the welcome.blade.php file will be like the code above.

Testing Laravel Analytics

Contoh data laravel analytics

And now let's try by opening our laravel project in the browser. As a result, we have successfully displayed data from google analytics in our laravel project using the laravel analytics package from spatie. If later the result is empty or does not display anything, it means that it is in the process of propagation. Please wait, the data will appear in Google Analytics in our Laravel project.


To be able to retrieve or display other google analytics data, you can read the documentation in the github.com/spatie/laravel-analytics repository. In the repository, examples of how to fetch data from google analytics have been provided, such as Total Visitors and Page Views, Most Visited Pages, Top Referrers, User Types, Top Browsers and others.

Conclusion

OK, we have successfully displayed or integrated google analytics in the laravel project. To be able to display google analytics data in laravel, we have gone through the steps between starting with registering a google analytics account, getting google analytics view_id, registering google cloud platform to get a key in JSON form, registering a new user in google analytics with the email that has been obtained at JSON file (obtained from GCP service account) to install laravel analytics package. By directly integrating Google Analytics in Laravel projects, we can easily monitor traffic or website performance directly from the dashboard without having to open Google Analytics in a new tab.

If there are criticisms, suggestions or anything that you want to discuss, please write a comment in the comment form provided below. And if you have other ways to integrate Google Analytics in Laravel, you can also share in the comments form. See you

Data illustrations by Storyset

Tinggalkan Komentar
Loading Comments