Add Google Analytics Code to Filament: Render Hooks

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.

No comments or questions yet...

Like our articles?

Become a Premium Member for $129/year or $29/month
What else you will get:
  • 59 courses (1057 lessons, total 42 h 44 min)
  • 78 long-form tutorials (one new every week)
  • access to project repositories
  • access to private Discord

Recent Premium Tutorials