Laravel

How to integrate google analytics with Laravel websites?

Share your learning

Learn about to integrate google analytics with Laravel in this tutorial.

Google Analytics is a powerful tool that allows website owners to track and analyze user behavior on their sites. It provides valuable insights into website traffic, user demographics, popular content, and much more. 

Integrating Google Analytics with your Laravel website can help you make data-driven decisions to improve user experience and optimize your online presence. 

In this article, we will walk through the process of integrating Google Analytics with a Laravel website, step by step, with clear examples for each stage.

Prerequisites

Before we begin, make sure you have the following:

  1. A working Laravel application.
  2. A Google Analytics account. If you don’t have one, sign up for free at https://analytics.google.com.

Step 1: Set up Google Analytics Account to integrate with laravel

If you already have a Google Analytics account, skip this step. Otherwise, sign in to your Google account and navigate to https://analytics.google.com. Click on the “Start Measuring” button and follow the instructions to set up your Google Analytics property.

Once you have set up the property, you will be provided with a Tracking ID. This ID is essential for integrating Google Analytics into your Laravel website.

Step 2: Install Required Packages

In your Laravel project, you will need to install the “spatie/laravel-analytics” package to simplify the integration process. This package provides a Laravel wrapper for the Google Analytics Reporting API. Open your terminal and run the following command:

composer require spatie/laravel-analytics

Step 3: Configure Package

After installing the package, open your Laravel application’s .env file and add the following lines:

ANALYTICS_VIEW_ID=YOUR_GOOGLE_ANALYTICS_VIEW_ID
GOOGLE_ANALYTICS_CREDENTIALS=PATH_TO_YOUR_CREDENTIALS_JSON_FILE

Replace YOUR_GOOGLE_ANALYTICS_VIEW_ID with the View ID of the property you want to track (can be found in your Google Analytics account). Make sure you have set the appropriate permissions for the email associated with the credentials JSON file.

Step 4: Obtain Google Analytics Credentials

To access the Google Analytics API, you need to create credentials in the Google Cloud Console. Follow these steps:

  1. Go to the Google Cloud Console at https://console.cloud.google.com.
  2. Create a new project or select an existing one.
  3. In the sidebar, navigate to “APIs & Services” > “Credentials.”
  4. Click on “Create Credentials” and choose “Service Account.”
  5. Fill in the necessary details and grant the “Project” > “Editor” role to the service account.
  6. Click “Continue” and then “Done.”
  7. Locate the created service account under the “Service Accounts” tab and click on the ellipsis (three dots) button.
  8. Select “Create Key” and choose “JSON” as the key type. The JSON file containing your credentials will be downloaded.

Save the downloaded JSON file in a secure location within your Laravel project and update the GOOGLE_ANALYTICS_CREDENTIALS value in the .env file with the correct path.

Step 5: Implement Google Analytics Service

Now, let’s create a service that will interact with the Google Analytics Reporting API. In your Laravel application, create a new file named GoogleAnalytics.php in the app/Services directory.

// app/Services/GoogleAnalytics.php

namespace App\Services;

use Spatie\Analytics\Analytics;
use Spatie\Analytics\Period;

class GoogleAnalytics
{
    protected $analytics;

    public function __construct(Analytics $analytics)
    {
        $this->analytics = $analytics;
    }

    public function getWebsiteVisitors($days = 7)
    {
        return $this->analytics->fetchTotalVisitorsAndPageViews(Period::days($days));
    }

    // Add more methods as needed for different analytics data
}

Step 6: Utilize the Google Analytics Service to integrate with laravel

Now that we have our service set up, we can use it in our controllers or views to fetch Google Analytics data. Let’s create a simple example to display the total number of website visitors in the last 7 days.First, add a route in your web.php file:

// routes/web.php

use App\Services\GoogleAnalytics;

Route::get('/', function (GoogleAnalytics $ga) {
    $visitorsData = $ga->getWebsiteVisitors(7);
    $totalVisitors = $visitorsData->sum('visitors');

    return view('welcome', compact('totalVisitors'));
});

Next, create a corresponding Blade view file (welcome.blade.php in this example):

<!-- resources/views/welcome.blade.php -->

<!DOCTYPE html>
<html>
<head>
    <title>Google Analytics Integration</title>
</head>
<body>
    <h1>Total Visitors in the Last 7 Days: {{ $totalVisitors }}</h1>
</body>
</html>

Step 7: Test the Integration

Finally, visit your Laravel website and navigate to the route you created. The view should display the total number of website visitors in the last 7 days, fetched from Google Analytics.

Conclusion

Integrating Google Analytics with your Laravel website opens up a world of possibilities for analyzing user behavior and making data-driven decisions. In this article, we covered the step-by-step process of integrating Google Analytics with a Laravel website, from obtaining credentials to creating a custom service to fetch analytics data. Remember to explore the Google Analytics Reporting API documentation for more advanced data retrieval and analysis.

By leveraging the power of Google Analytics, you can gain valuable insights into your website’s performance and user engagement, leading to better user experiences and improved business outcomes. Happy tracking!

Satpal

Recent Posts

How to Switch PHP Versions in XAMPP Easily: Managing Multiple PHP Versions on Ubuntu

Today we are going to learn about managing multiple PHP versions on ubuntu with xampp.…

1 year ago

How to Use Coding to Improve Your Website’s SEO Ranking?

Let's understand about how to use coding to improve your website's SEO. In today’s computerized…

1 year ago

Most Important Linux Commands for Web Developers

Let's understand the most important linux commands for web developers. Linux, as an open-source and…

1 year ago

Top 75+ Laravel Interview Questions Asked by Top MNCs

Today we are going to discuss top 75+ Laravel interview questions asked by top MNCs.Laravel,…

1 year ago

Mailtrap Integration for Email Testing with Laravel 10

Today we will discuss about the Mailtrap integration with laravel 10 .Sending and receiving emails…

1 year ago

Firebase Cloud Messaging (FCM) with Ionic 6: Push Notifications

Today we are going to integrate FCM (Firebase Cloud Messaging) push notifications with ionic application.Firebase…

1 year ago