How to Add Google Analytics to Laravel Website
Adding Google Analytics to your Laravel website is one of the fastest ways to understand exactly how users interact with your application. In this tutorial, we’ll walk through an easy-to-follow path to get Google Analytics up and running on your Laravel project, covering everything from a simple tracking code installation to a more structured, maintainable approach.
Why Add Google Analytics to Your Laravel Site?
Before jumping into the "how," let's briefly cover the "why." Integrating Google Analytics isn't just about tracking page views, it's about getting real data to make smarter decisions. It’s the digital equivalent of understanding foot traffic and customer behavior in a physical store.
With Google Analytics, you can answer critical business questions like:
- Who are my users? Understand their demographics, interests, and what devices they use to access your site.
- How did they find me? See which channels (like Google search, social media, or paid ads) are driving the most traffic.
- What are they doing? Track which pages are most popular, how long users stay, and what paths they take through your site.
- Are my marketing efforts working? Measure conversions, whether that’s a contact form submission, a product purchase, or a new user registration.
In short, it moves you from operating on gut feelings to making data-backed decisions that can grow your business.
First,
Create a new Laravel project
If you have an existing one you are familiar with connecting it to Heroku, Netlify, or AWS, feel free to use it. Or you can start a simple project from scratch.
1. Open terminal and change directory to a new location for this Laravel project or choose another path that's easy for you.
cd MyProject
laravel new blogg
cd blogg2. After finishing our download, run these other commands.
npm install && php artisan serveLet's find the small bit of information that connects your Laravel application with your Google Analytics account.
Finding Your Measurement ID in GA4
Every website you track in Google Analytics 4 has a unique "Measurement ID." This ID tells Google where to send the tracking data. Here’s how to find it:
- Navigate to your Google Analytics account.
- Click the Admin icon (the gear) in the bottom-left corner.
- In the Property column, make sure your desired GA4 property is selected.
- Click on Data Streams, then select the web stream for your website. It will likely be named after your domain.
- On the next screen, your Measurement ID (formatted as "G-XXXXXXXXXX") will be in the top right. Copy this ID, you'll need it in a moment.
If you scroll down this page, you’ll also see a section called "View tag instructions." Clicking this and selecting the "Install manually" tab will give you the full JavaScript tracking code, known as the Global Site Tag (gtag.js). We'll also use this in the next step.
Method 1: Manually Adding the GA4 Tag to Your Layout
This is the quickest way to get Google Analytics working. It involves directly placing the Global Site Tag into your main application layout file so it loads on every page.
Step 1: Locate Your Main Blade Layout File
Most Laravel applications have a main layout file that contains the fundamental HTML structure, including the <html>, <head>, and <body> tags. All other pages extend this layout.
By default, this is often located at:
resources/views/layouts/app.blade.php
Open this file in your code editor.
Step 2: Use an Environment Variable for Your Measurement ID
While you could just paste the entire Google Analytics script directly into your layout, hardcoding your Measurement ID isn't a great practice. It makes it harder to manage different IDs for development, staging, and production environments.
A much cleaner way is to store the ID in your environment file (.env). Open your .env file and add a new line at the bottom:
GA_MEASUREMENT_ID=G-XXXXXXXXXX
Replace G-XXXXXXXXXX with your actual Measurement ID you copied earlier.
Next, to make this variable easily accessible within your application, add it to a configuration file. A good place for this is config/services.php.
<?php
return [
// ... other services
'google' => [
'analytics_id' => env('GA_MEASUREMENT_ID'),
],
],Pro-tip: After adding a new config variable, run php artisan config:cache in production to make sure the app picks up the changes. During local development, this isn't usually necessary.
Step 3: Add the Tracking Code to Your Layout
Now, go back to your layout file (resources/views/layouts/app.blade.php). Paste the Global Site Tag you got from Google Analytics just before the closing </head> tag. Then, replace the hard-coded G-XXXXXXXXXX with a call to your new config variable.
Your final code should look like this:
<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>My Awesome Laravel App</title>
{{-- Other meta tags, CSS links, etc. --}}
<!-- Global Site Tag (gtag.js) - Google Analytics -->
<script async src="https://www.googletagmanager.com/gtag/js?id={{ config('services.google.analytics_id') }}"></script>
<script>
window.dataLayer = window.dataLayer || [],
function gtag(){dataLayer.push(arguments),}
gtag('js', new Date()),
gtag('config', '{{ config('services.google.analytics_id') }}'),
</script>
</head>
<body>
{{-- Your app content --}}
</body>
</html>And that’s it! With this code in place, Google Analytics will now load on every page of your site that uses this layout.
Method 2: Using a Dedicated Blade Partial
For better organization and code reuse, you can put the Google Analytics script in its own separate file called a "partial." This keeps your main layout file clean and makes it easier to manage tracking scripts.
Step 1: Create a Partial for Analytics
Create a new folder inside resources/views named partials. Inside this new folder, create a file named analytics.blade.php.
resources/views/partials/analytics.blade.php
Step 2: Move the Script to the Partial
Cut the entire Google Analytics script (the two <script> tags) from your app.blade.php file and paste it into your new partial, analytics.blade.php:
{{-- resources/views/partials/analytics.blade.php --}}
<!-- Global Site Tag (gtag.js) - Google Analytics -->
<script async src="https://www.googletagmanager.com/gtag/js?id={{ config('services.google.analytics_id') }}"></script>
<script>
window.dataLayer = window.dataLayer || [],
function gtag(){dataLayer.push(arguments),}
gtag('js', new Date()),
gtag('config', '{{ config('services.google.analytics_id') }}'),
</script>Note: We're assuming you’ve already set up the environment variable as described in Method 1.
Step 3: Include the Partial in Your Layout
Finally, go back to your app.blade.php file and use Blade's @include directive to pull in the script. Add this directive before the closing </head> tag:
<!-- Head Content -->
@if(!app()->environment('local'))
@include('partials.analytics')
@endifThis way, the script will only load outside of your local environment, preventing unnecessary tracking during development.
This approach is clean and modular. If you ever want to add or remove tracking scripts or other analytics code (like from a Facebook Pixel), you can add them to their own partial or extend this one.
Verifying Your Analytics Installation
After you've implemented either Method 1 or Method 2, you'll want to make sure it is working correctly.
Option 1: Use Google Analytics Real-Time Report
This is the easiest way. Open your site in a browser and then go to your Google Analytics. In the left navigation, click on Reports > Real-time. You should see at least one active user on your site. If you aren’t seeing the number go up, wait a few minutes and try again.
Option 2: Chrome Developer Tools
Right-click on your page in Chrome and select Inspect to open the Developer Tools. Click the Network tab at the top. Then in the filter box, type collect and refresh your page. You should see one or more requests appearing in the list to a URL that contains google-analytics.com and your Measurement ID. This confirms that your browser is successfully sending data to Google Analytics.
Option 3: The Gtag Assistant Chrome Extension
This is a free browser extension developed by Google that helps you troubleshoot your installation. Install it from the Chrome Web Store and navigate to a page on your site, then use the extension's tooltip. It should show you whether the Gtag is correctly detecting and collecting data, giving you specific messages to help you debug.
Final Thoughts
Integrating Google Analytics into your Laravel application is a smart move for any data-driven development. Whether you choose to directly embed the tracking code in your layout or use a modular approach, you’re taking important steps to better understand your audience and improve their experience. Ultimately, this enhances your ability to make informed decisions that drive business success.
Related Articles
How to Connect Facebook to Google Data Studio: The Complete Guide for 2026
Connecting Facebook Ads to Google Data Studio (now called Looker Studio) has become essential for digital marketers who want to create comprehensive, visually appealing reports that go beyond the basic analytics provided by Facebook's native Ads Manager. If you're struggling with fragmented reporting across multiple platforms or spending too much time manually exporting data, this guide will show you exactly how to streamline your Facebook advertising analytics.
Appsflyer vs Mixpanel: Complete 2026 Comparison Guide
The difference between AppsFlyer and Mixpanel isn't just about features—it's about understanding two fundamentally different approaches to data that can make or break your growth strategy. One tracks how users find you, the other reveals what they do once they arrive. Most companies need insights from both worlds, but knowing where to start can save you months of implementation headaches and thousands in wasted budget.
DashThis vs AgencyAnalytics: The Ultimate Comparison Guide for Marketing Agencies
When it comes to choosing the right marketing reporting platform, agencies often find themselves torn between two industry leaders: DashThis and AgencyAnalytics. Both platforms promise to streamline reporting, save time, and impress clients with stunning visualizations. But which one truly delivers on these promises?