Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

mesqueeb's avatar

How to add Google Analytics to Laravel?

Hello Community, I've created my first website with Laravel. I want to add Google Analytics now.

I'm still new to G.A. and have looked for some simple guides how to implement this into my website. But I can't find any simple guides for the Laravel framework. Most guides expect you to fully understand Google Analytics already! XD

Can anyone point me in the correct direction?

0 likes
6 replies
DmytroOlefyrenko's avatar

Hi! Just go to Admin section at Google Analytics. Then in Property level go to Tracking Info -> Tracking Code and copy tracking code into html views of your Laravel app. The tracking code looks like:

<script>
  (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
  (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
  m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
  })(window,document,'script','https://www.google-analytics.com/analytics.js','ga');

  ga('create', 'YOUR_ID', 'auto');
  ga('send', 'pageview');

</script>
mesqueeb's avatar

@DmytroOlefyrenko Waht about the <?php include_once("analyticstracking.php") ?> Do I need to add this? And G.A. said something about having to "create a analyticstracking.php file" ?

mcenroe's avatar

Laravel is no different than any other website, you just need to grab the analytics code from your analytics account and then paste it before the body clossing tag. If you are using different footers throughout your website, then you can place the code on a blade file and @include it on the different footer templates that you might have in your project.

https://laravel.com/docs/5.4/blade#including-sub-views

mesqueeb's avatar

@DmytroOlefyrenko @mcenroe Thank you so much. 2 more questions:

  1. Can I add the analytics script just after opening the <head> tag? or better below the <body> tag?

  2. Do I need to include this line? <?php include_once("analyticstracking.php") ?>

mcenroe's avatar
mcenroe
Best Answer
Level 5

@mesqueeb

  1. it used to be recommended to include it before the body closing tag when it wasn't asynchronous, now that it is you can include it in the head or before the body closing tag, as you like.

  2. In Laravel you don't need to require files that way, what you can do is to make a subview like @DmytroOlefyrenko and I explained just above. Just place the code inside a file, name it analytics.blade.php and save it in your Resources / Views folder. Then within your footer.blade.php or header.blade.php just place the following line of code where you want to analytics script to be included: @include('analytics') . The @include blade directive then will look for the analytics.blade.php file and include it there.

4 likes

Please or to participate in this conversation.