In this short snippet, you will learn the ways to integrate Google Analytics 4 in your Laravel Inertia website.
We assume that you have created Google Analytics 4 property and then have the code already prepared. It will look as follows.
Step 1: Create Google Analytics and Copy Analytics Code
We assume that you have created Google Analytics 4 property and then have the code already prepared. It will look as follows.
<script async src="https://www.googletagmanager.com/gtag/js?id=G-XXX"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag() {
dataLayer.push(arguments);
}
gtag("js", new Date());
gtag("config", "G-XXX");
</script>Step 2: Update Laravel Blade Base Layout with Analytics Code
Next, you need to update the "views/app.blade.php" with the analytics base code so that it's referenced for all of the pages that extend it. For the full code example, it will be like the code below.
<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}" class="scroll-smooth">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title inertia>{{ config('app.name', 'Laravel Inertia GA 4') }}</title>
<link rel="icon" type="image/png" href="{{ url('/favicon.png') }}">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Roboto:wght@400;500;700&display=swap" rel="stylesheet">
@vite(['resources/css/app.css', 'resources/js/app.js'])
@inertiaHead
</head>
<body class="font-sans antialiased bg-slate-50 dark:bg-slate-800">
@inertia
@production
<script async src="https://www.googletagmanager.com/gtag/js?id=G-XXX"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag() {
dataLayer.push(arguments);
}
</script>
@endproduction
</body>
</html>Step 3: Update app.js to Fire GA 4 Event
Now when the page navigates you will have to fire an event to allow Google Analytics 4 to collect the page views data. To do that you can listen to the "navigate" event on the "resources/js/app.js".
/**
* Track Page and Send to Google Analytic
* */
if (process.env.NODE_ENV === "production") {
Inertia.on("navigate", (event) => {
gtag("js", new Date());
gtag("config", "G-XXX");
});
}I hope this short snippet helps and cheers, happy coding! Do share it with your friends if you find it helpful.