Skip to main content
Tutorial Free

Add Google Analytics Code to Filament: Render Hooks

October 12, 2023
2 min read

Installing the Google Analytics script in Filament is not that easy. Especially once you open the resources folder and realize there are no views. So, where do you put the script? You use Filament Theme Hooks!


Adding the Script

Since Filament does not publish its views - you need to use render hooks. We will use the panels::head.start hook to add our GA script after the opening <head> tag:

Providers/Filament/AdminPanelProvider.php

public function panel(Panel $panel): Panel
{
return $panel
->default()
->id('admin')
->path('admin')
->login()
->colors([
// ...
])
->discoverResources(in: app_path('Filament/Resources'), for: 'App\\Filament\\Resources')
->discoverPages(in: app_path('Filament/Pages'), for: 'App\\Filament\\Pages')
->pages([
// ...
])
->discoverWidgets(in: app_path('Filament/Widgets'), for: 'App\\Filament\\Widgets')
->widgets([
// ...
])
->renderHook(
'panels::head.start',
fn () => view('analyticsTag'),
)
->middleware([
// ...
])
->authMiddleware([
// ...
]);
}

Once we register the hook, we must create the view to render the script:

resources/views/analyticsTag.blade.php

<script async src="https://www.googletagmanager.com/gtag/js?id=XXXXXXXXXXXXXXXXXXXXX"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
 
gtag('config', 'XXXXXXXXXXXXXXXXXXXXX');
</script>

That's it! Load the page, and you will see your tag added to the <head> tag:


If you want more Filament examples, you can find more real-life projects on our FilamentExamples.com.

Enjoyed This Tutorial?

Get access to all premium tutorials, video and text courses, and exclusive Laravel resources. Join our community of 10,000+ developers.

Recent Courses on Laravel Daily

Laravel 13 Starter Kit Teams and Customizations

10 lessons
33 min

Testing in Laravel 13 For Beginners

26 lessons
1 h 41 min read

Laravel 13 Eloquent: Expert Level

41 lessons
1 h 34 min
Олег Ільницький avatar
Олег Ільницький

And how to add this script only to selected pages?