PHPackages                             angallego/laravel-gtm - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Utility &amp; Helpers](/categories/utility)
4. /
5. angallego/laravel-gtm

ActiveLibrary[Utility &amp; Helpers](/categories/utility)

angallego/laravel-gtm
=====================

Google Tag Manager integration for Laravel

2.3.0(9y ago)1397MITPHPPHP &gt;=5.4.0

Since Jun 4Pushed 6y agoCompare

[ Source](https://github.com/angallego/laravel-googletagmanager)[ Packagist](https://packagist.org/packages/angallego/laravel-gtm)[ Docs](https://github.com/spatie/laravel-googletagmanager)[ RSS](/packages/angallego-laravel-gtm/feed)WikiDiscussions master Synced today

READMEChangelogDependenciesVersions (14)Used By (0)

I'm not owner of this package. It is a modification.
====================================================

[](#im-not-owner-of-this-package-it-is-a-modification)

Google Tag Manager integration for Laravel
==========================================

[](#google-tag-manager-integration-for-laravel)

[![Latest Version on Packagist](https://camo.githubusercontent.com/853c9baf411861a1a4e5cd1f0eaa8b113545d9863e708773038c42caebcfba65/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f7370617469652f6c61726176656c2d676f6f676c657461676d616e616765722e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/spatie/laravel-googletagmanager)[![Software License](https://camo.githubusercontent.com/55c0218c8f8009f06ad4ddae837ddd05301481fcf0dff8e0ed9dadda8780713e/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6c6963656e73652d4d49542d627269676874677265656e2e7376673f7374796c653d666c61742d737175617265)](LICENSE.md)[![Quality Score](https://camo.githubusercontent.com/ab1ef9ca215f8e47876d1c2d2a3de0b80cf8da7d1594711e7dea071ec8ecdc30/68747470733a2f2f696d672e736869656c64732e696f2f7363727574696e697a65722f672f7370617469652f6c61726176656c2d676f6f676c657461676d616e616765722e7376673f7374796c653d666c61742d737175617265)](https://scrutinizer-ci.com/g/spatie/laravel-googletagmanager)[![SensioLabsInsight](https://camo.githubusercontent.com/ee9b6ceb4bfb11e17ed3d7d3e69194889ededc1cf9b1ee358e3deca22db8f12a/68747470733a2f2f696d672e736869656c64732e696f2f73656e73696f6c6162732f692f62613761623234392d333363642d343837382d613139362d3332623963383039633736392e7376673f7374796c653d666c61742d737175617265)](https://insight.sensiolabs.com/projects/ba7ab249-33cd-4878-a196-32b9c809c769)[![Total Downloads](https://camo.githubusercontent.com/991b7b237b1d263e22aeda4452acd6785636e5697ec6056a0b71dbdbb13b25ae/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f7370617469652f6c61726176656c2d676f6f676c657461676d616e616765722e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/spatie/laravel-googletagmanager)

An easy [Google Tag Manager](http://www.google.com/tagmanager/) implementation for your Laravel 5 application.

Laravel 4 version: [spatie/laravel4-googletagmanager](https://github.com/spatie/laravel4-googletagmanager)

Spatie is a webdesign agency in Antwerp, Belgium. You'll find an overview of all our open source projects [on our website](https://spatie.be/opensource).

Postcardware
------------

[](#postcardware)

You're free to use this package (it's [MIT-licensed](LICENSE.md)), but if it makes it to your production environment you are required to send us a postcard from your hometown, mentioning which of our package(s) you are using.

Our address is: Spatie, Samberstraat 69D, 2060 Antwerp, Belgium.

The best postcards will get published on the open source page on our website.

Google Tag Manager
------------------

[](#google-tag-manager)

Google Tag Manager allows you manage tracking and marketing optimization with AdWords, Google Analytics, et al. without editing your site code. One way of using Google Tag Manager is by sending data through a `dataLayer` variable in javascript after the page load and on custom events. This package makes managing the data layer easy.

For concrete examples of what you want to send throught the data layer, check out Google Tag Manager's [Developer Guide](https://developers.google.com/tag-manager/devguide).

You'll also need a Google Tag Manager ID, which you can retrieve by [signing up](https://tagmanager.google.com/#/home) and creating an account for your website.

Install
-------

[](#install)

You can install the package via Composer:

```
$ composer require spatie/laravel-googletagmanager
```

Start by registering the package's the service provider and facade:

```
// config/app.php

'providers' => [
  ...
  'Spatie\GoogleTagManager\GoogleTagManagerServiceProvider',
],

'aliases' => [
  ...
  'GoogleTagManager' => 'Spatie\GoogleTagManager\GoogleTagManagerFacade',
],
```

*The facade is optional, but the rest of this guide assumes you're using the facade.*

Next, publish the config files:

```
$ php artisan vendor:publish --provider="Spatie\GoogleTagManager\GoogleTagManagerServiceProvider" --tag="config"
```

Optionally publish the view files. It's **not** recommended to do this unless necessary so your views stay up-to-date in future package releases.

```
$ php artisan vendor:publish --provider="Spatie\GoogleTagManager\GoogleTagManagerServiceProvider" --tag="views"
```

If you plan on using the [flash-functionality](#flashing-data-for-the-next-request) you must install the middleware:

```
// app/Http/Kernel.php

    protected $middleware = [
        ...
        'Spatie\GoogleTagManager\GoogleTagManagerMiddleware',
        ...
    ];
```

Configuration
-------------

[](#configuration)

The configuration file is fairly simple.

```
return [

    /*
     * The Google Tag Manager id, should be a code that looks something like "gtm-xxxx".
     */
    'id' => '',

    /*
     * Enable or disable script rendering. Useful for local development.
     */
    'enabled' => true,

    /*
     * If you want to use some macro's you 'll probably store them
     * in a dedicated file. You can optionally define the path
     * to that file here and we will load it for you.
     */
    'macroPath' => '',

];
```

During development, you don't want to be sending data to your production's tag manager account, which is where `enabled` comes in.

Example setup:

```
return [
    'id' => 'GTM-XXXXXX',
    'enabled' => env('APP_ENV') === 'production',
    'macroPath => app_path('Services/GoogleTagManager/Macros.php'),
];
```

Usage
-----

[](#usage)

### Basic Example

[](#basic-example)

First you'll need to include Google Tag Manager's script. Google's docs recommend doing this right after the body tag.

```
{{-- layout.blade.php --}}

  {{-- ... --}}

    @include('googletagmanager::script')
    {{-- ... --}}

```

Your base dataLayer will also be rendered here. To add data, use the `set()` function.

```
// HomeController.php

public function index()
{
    GoogleTagManager::set('pageType', 'productDetail');

    return view('home');
}
```

This renders:

```

    dataLayer = [{"pageType":"productDetail"}];
    /* Google Tag Manager's script */

```

#### Flashing data for the next request

[](#flashing-data-for-the-next-request)

The package can also set data to render on the next request. This is useful for setting data after an internal redirect.

```
// ContactController.php

public function getContact()
{
    GoogleTagManager::set('pageType', 'contact');

    return view('contact');
}

public function postContact()
{
    // Do contact form stuff...

    GoogleTagManager::flash('formResponse', 'success');

    return redirect()->action('ContactController@getContact');
}
```

After a form submit, the following dataLayer will be parsed on the contact page:

```

    dataLayer = [{"pageType":"contact","formResponse":"success"}];
    /* Google Tag Manager's script */

```

### Other Simple Methods

[](#other-simple-methods)

```
// Retrieve your Google Tag Manager id
$id = GoogleTagManager::id(); // GTM-XXXXXX

// Check whether script rendering is enabled
$enabled = GoogleTagManager::isEnabled(); // true|false

// Enable and disable script rendering
GoogleTagManager::enable();
GoogleTagManager::disable();

// Add data to the data layer (automatically renders right before the tag manager script). Setting new values merges them with the previous ones. Set als supports dot notation.
GoogleTagManager::set(['foo' => 'bar']);
GoogleTagManager::set('baz', ['ho' => 'dor']);
GoogleTagManager::set('baz.ho', 'doorrrrr');

// [
//   'foo' => 'bar',
//   'baz' => ['ho' => 'doorrrrr']
// ]
```

### Dump

[](#dump)

GoogleTagManager also has a `dump()` function to convert arrays to json objects on the fly. This is useful for sending data to the view that you want to use at a later time.

```
Product

```

```
$('[data-gtm-click]').on('click', function() {
    dataLayer.push({
        'event': 'productClick',
        'ecommerce': {
            'click': {
                'products': $(this).data('gtm-product')
            }
        }
        'eventCallback': function() {
            document.location = $(this).attr('href');
        }
    });
});
```

### DataLayer

[](#datalayer)

Internally GoogleTagManager uses the DataLayer class to hold and render data. This class is perfectly usable without the rest of the package for some custom implementations. DataLayer is a glorified array that has dot notation support and easily renders to json.

```
$dataLayer = new Spatie\GoogleTagManager\DataLayer();
$dataLayer->set('ecommerce.click.products', $products->toJson());
echo $dataLayer->toJson(); // {"ecommerce":{"click":{"products":"..."}}}
```

If you want full access to the GoogleTagManager instances' data layer, call the `getDataLayer()` function.

```
$dataLayer = GoogleTagManager::getDataLayer();
```

### Macroable

[](#macroable)

Adding tags to pages can become a repetitive process. Since this package isn't supposed to be opinionated on what your tags should look like, the GoogleTagManager is macroable.

```
GoogleTagManager::macro('impression', function ($product) {
    GoogleTagManager::set('ecommerce', [
        'currencyCode' => 'EUR',
        'detail' => [
            'products' => [ $product->getGoogleTagManagerData() ]
        ]
    ]);
});

GoogleTagManager::impression($product);
```

In the configuration you can optionally set the path to the file that contains your macros.

Changelog
---------

[](#changelog)

Please see [CHANGELOG](CHANGELOG.md) for more information what has changed recently.

Contributing
------------

[](#contributing)

Please see [CONTRIBUTING](CONTRIBUTING.md) for details.

Security
--------

[](#security)

If you discover any security related issues, please email  instead of using the issue tracker.

Credits
-------

[](#credits)

- [Sebastian De Deyne](https://github.com/sebastiandedeyne)
- [All Contributors](../../contributors)

About Spatie
------------

[](#about-spatie)

Spatie is a webdesign agency in Antwerp, Belgium. You'll find an overview of all our open source projects [on our website](https://spatie.be/opensource).

License
-------

[](#license)

The MIT License (MIT). Please see [License File](LICENSE.md) for more information.

###  Health Score

31

—

LowBetter than 71% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity15

Limited adoption so far

Community10

Small or concentrated contributor base

Maturity65

Established project with proven stability

 Bus Factor1

Top contributor holds 64% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~51 days

Recently: every ~153 days

Total

13

Last Release

3323d ago

Major Versions

1.2.2 → v2.0.02015-06-11

### Community

Maintainers

![](https://www.gravatar.com/avatar/4d48ea31889a58d70fa9a6b0d205519a70cdacfb07e6c92ee2bb6074b71abf0e?d=identicon)[angallego](/maintainers/angallego)

---

Top Contributors

[![sebastiandedeyne](https://avatars.githubusercontent.com/u/1561079?v=4)](https://github.com/sebastiandedeyne "sebastiandedeyne (48 commits)")[![freekmurze](https://avatars.githubusercontent.com/u/483853?v=4)](https://github.com/freekmurze "freekmurze (15 commits)")[![angallego](https://avatars.githubusercontent.com/u/23311807?v=4)](https://github.com/angallego "angallego (10 commits)")[![pdbreen](https://avatars.githubusercontent.com/u/1670907?v=4)](https://github.com/pdbreen "pdbreen (2 commits)")

---

Tags

spatielaravelGoogle Tag Managerlaravel-googletagmanager

### Embed Badge

![Health badge](/badges/angallego-laravel-gtm/health.svg)

```
[![Health](https://phpackages.com/badges/angallego-laravel-gtm/health.svg)](https://phpackages.com/packages/angallego-laravel-gtm)
```

###  Alternatives

[spatie/laravel-data

Create unified resources and data transfer objects

1.7k27.1M477](/packages/spatie-laravel-data)[spatie/laravel-analytics

A Laravel package to retrieve Google Analytics data.

3.3k5.6M49](/packages/spatie-laravel-analytics)[spatie/laravel-googletagmanager

Google Tag Manager integration for Laravel

4463.4M5](/packages/spatie-laravel-googletagmanager)[spatie/laravel-login-link

Quickly login to your local environment

4361.2M1](/packages/spatie-laravel-login-link)[spatie/laravel-livewire-wizard

Build wizards using Livewire

407946.2k2](/packages/spatie-laravel-livewire-wizard)[statikbe/laravel-cookie-consent

Cookie consent modal for EU

209387.2k](/packages/statikbe-laravel-cookie-consent)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
