How to Add Google Analytics 4 (GA4) Tracking Code to Laravel

If you want to integrate Google Analytics tracking into your Laravel application without relying on a package, this guide is for you.

Follow these six straightforward steps to set up Google Analytics version 4 for your Laravel project.

Step 1: Obtain Google Analytics Measurement ID

To integrate Google Analytics into your Laravel application, you will need to obtain the Measurement ID. Follow these steps:

  1. Sign in to your Google Analytics account. If you don’t have an account, create a new one.
  2. Create a new property specifically for your Laravel application. This will generate a unique Measurement ID for tracking.
  3. To locate the Measurement ID, follow these steps:
    • Click on “Admin” (or the cogs icon) located at the bottom left of the page
    • Select or create the property associated with your Laravel application.
    • Navigate to the data streams section.
    • Click on “Stream Details.” You will find the Measurement ID, which typically starts with “G-” followed by a series of alphanumeric characters (e.g., G-XXXXXXXXXX).
Screenshot of the GA Admin Area Showing the Measurement ID of a GA4 Property

Step 2: Configure the Environment Variables

Open the .env file located in the root directory of your Laravel project. Insert the following environment variables:

GA_MEASUREMENT_ID=G-XXXXXXXXXX

Replace 'G-XXXXXXXXXX' with your actual measurement ID, as obtained in Step 1.

Step 3: Add variables to the Laravel Configuration

Open /config/services.php and add your key and secret to the array, as shown below:

return [

    /*
    |--------------------------------------------------------------------------
    | Third Party Services
    |--------------------------------------------------------------------------
    |
    | This file is for storing the credentials for third party services such
    | as Mailgun, Postmark, AWS and more. This file provides the de facto
    | location for this type of information, allowing packages to have
    | a conventional file to locate the various service credentials.
    |
    */

    // .. Other services ..

    // Configure Google Analytics 4 (GA4) measurement_id
    'ga4' => [
        'measurementId' => env('GA_MEASUREMENT_ID'),
    ]
];

We include these variables here so that we can access them later on in our code using config('services.ga4.measurementId').

While you could also use env('GA_MEASUREMENT_ID'), it is not recommended as it can potentially break your application when config caching is enabled. To learn more about this, please refer to the article: The Safe Way to Use env Variables in Laravel.

Step 4: Add Google Analytics Tracking Code

  • Open your Laravel project and locate the main layout file, typically located at resources/views/layouts/app.blade.php.
  • In the <head> section of the layout file, add the following Google Analytics tracking code, replacing “G-XXXXXXXXXX” with your Measurement ID:
<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
<head>
    <script async src="https://www.googletagmanager.com/gtag/js?id={{ config('services.ga4.measurementId') }}"></script>
    <script>
        window.dataLayer = window.dataLayer || [];
        function gtag(){dataLayer.push(arguments);}
        gtag('js', new Date());
        gtag('config', '{{ config('services.ga4.measurementId') }}');
    </script>
</head>
<body>
</body>
</html>

Step 5: Include Layout File in Views

  • Make sure that your views extend the main layout file (app.blade.php) or include it if you are using a different layout.
  • This can typically be done by adding @extends('layouts.app') at the top of your view files.

Step 6: Test Google Analytics Tracking

  • Once you have added the tracking code and included the layout file in your views, you can test if Google Analytics tracking is working correctly.
  • Visit your Laravel application in a web browser, and then go to your Google Analytics account.
  • Navigate to the “Realtime” section in Google Analytics and check if your website is showing up as an active user.

By following these steps, you can add Google Analytics tracking to your Laravel application using Google Analytics version 4. Remember to replace “G-XXXXXXXXXX” with your actual Measurement ID. Happy tracking!

Note that following the steps in this guide allows you to collect data and send it to your analytics environment for viewing and analysis on analytics.google.com. If you need to retrieve and process data within your Laravel application, consider exploring the Laravel Analytics package by Spatie. This package provides functionality to integrate and work with Google Analytics data in your Laravel application.

This entry is part 3 of 3 in the series Google Integration

  1. How to Send Email With Laravel Using Gmail
  2. How to Add Google reCAPTCHA v3 to Your Laravel Form
  3. How to Add Google Analytics 4 (GA4) Tracking Code to Laravel

Johan van den Broek

Johan is the creator of laracoding.com. As a child, he began tinkering with various programming languages, many of which have been long forgotten today. Currently, he works exclusively with PHP, and his passion for programming remains to this day.

Leave a Reply

Your email address will not be published. Required fields are marked *

Recent Posts