spatie/laravel-googletagmanager

repository·main·Indexed 19 days ago

https://github.com/spatie/laravel-googletagmanager

A Laravel integration for Google Tag Manager that simplifies managing the JavaScript dataLayer. It allows developers to push tracking data, events, and ecommerce information directly from PHP code using methods like set(), push(), and flash(). The package includes built-in Blade views for script injection and a standalone DataLayer class for managing data with dot notation support.

Tokens
3.4K
Snippets
19
Records
22
Agent score
65%

What's inside spatie/laravel-googletagmanager

  1. Extend GoogleTagManager with macros

    main

    Since the package is Macroable, you can define custom helper methods to simplify repetitive tagging tasks. Register these in a Service Provider's boot method.

    // In a Service Provider
    GoogleTagManager::macro('impression', function ($product) {
        GoogleTagManager::set('ecommerce', [
            'currencyCode' => 'EUR',
            'detail' => [
                'products' => [ $product->getGoogleTagManagerData() ]
            ]
        ]);
    });
    
    // Usage in a controller
    GoogleTagManager::impression($product);
    GoogleTagManager::macro('impression', function ($product) {
        GoogleTagManager::set('ecommerce', [
            'currencyCode' => 'EUR',
            'detail' => [
                'products' => [ $product->getGoogleTagManagerData() ]
            ]
        ]);
    });
  2. Include Google Tag Manager scripts in your views

    main

    To render the GTM scripts and the base dataLayer, include the package's built-in views in your layout file. Google recommends placing the head script right after the opening <head> tag and the body script right after the opening <body> tag.

    {{-- layout.blade.php --}}
    <html
      <head>
        @include('googletagmanager::head')
        {{-- ... --}}
      </head>
      <body
        @include('googletagmanager::body')
        {{-- ... --}}
      </body>
    </html>
    <head>
      @include('googletagmanager::head')
    </head>
    <body>
      @include('googletagmanager::body')
    </body>
  3. Upgrade from 2.x to 3.x: Handle Type Annotations

    main

    When upgrading from version 2.x to 3.x, note that the package now has 100% type coverage. If you have extended any of the package's core classes, you must add the required parameter types to your method overrides to avoid type errors.

    Key classes to inspect for potential breaking changes in your extensions include:

    • Spatie\GoogleTagManager\DataLayer
    • Spatie\GoogleTagManager\GoogleTagManager
    • Spatie\GoogleTagManager\GoogleTagManagerMiddleware
  4. Upgrade from 2.x to 3.x: Register Macros in a Service Provider

    main

    In version 3.x, the macroPath configuration option has been removed. Instead of configuring a path in your configuration files, you must now register macros within a Service Provider's boot method using the GoogleTagManager::macro method.

    use Spatie\GoogleTagManager\GoogleTagManager;
    
    public function boot(): void
    {
        GoogleTagManager::macro('impression', function ($product) {
            GoogleTagManager::set('ecommerce', ['product' => $product->id]);
        });
    }
  5. Install the Google Tag Manager package

    main

    Install the package via Composer:

    composer require spatie/laravel-googletagmanager

    For Laravel 5.5 and up, the service provider and facade are automatically registered.

    For Laravel 5.4 or below, manually register the provider and facade in config/app.php:

    'providers' => [
        ...
        Spatie\GoogleTagManager\GoogleTagManagerServiceProvider::class,
    ],
    
    'aliases' => [
        ...
        'GoogleTagManager' => Spatie\GoogleTagManager\GoogleTagManagerFacade::class,
    ],

    After installation, publish the configuration file:

    php artisan vendor:publish --provider="Spatie\GoogleTagManager\GoogleTagManagerServiceProvider" --tag="config"
  6. Flash data for the next request

    main

    To send data to the dataLayer after an internal redirect (e.g., after a form submission), use the flash() method.

    Requirement: You must add Spatie\GoogleTagManager\GoogleTagManagerMiddleware::class to your app/Http/Kernel.php middleware stack, ensuring it is placed after Illuminate\Session\Middleware\StartSession::class.

    // In your controller
    public function postContact()
    {
        // ... logic ...
        GoogleTagManager::flash('formResponse', 'success');
    
        return redirect()->action('ContactController@getContact');
    }
    GoogleTagManager::flash('formResponse', 'success');
  7. Publish the Google Tag Manager configuration and views

    main

    To customize the package behavior or the default views, you can publish the configuration and view files to your application's resources directory using the following Artisan commands:

    To publish the configuration file: php artisan vendor:publish --tag=config

    To publish the views: php artisan vendor:publish --tag=views

    php artisan vendor:publish --tag=config
    php artisan vendor:publish --tag=views
  8. Use the DataLayer class independently

    main

    The Spatie\GoogleTagManager\DataLayer class is a standalone utility that manages data with dot notation support and provides JSON serialization. You can use it without the full package.

    use Spatie\GoogleTagManager\DataLayer;
    
    $dataLayer = new DataLayer();
    $dataLayer->set('ecommerce.click.products', $products->toJson());
    echo $dataLayer->toJson(); // {"ecommerce":{"click":{"products":"..."}}}
    $dataLayer = new Spatie\GoogleTagManager\DataLayer();
    $dataLayer->set('ecommerce.click.products', $products->toJson());
    echo $dataLayer->toJson();
  9. Flash push data for the next request

    main

    If you want to flash data that uses window.dataLayer.push() (to avoid overwriting existing keys and instead append to the push queue), use flashPush().

    public function callback()
    {
        if ($user->wasRecentlyCreated) {
            GoogleTagManager::flashPush(['event' => 'sign_up', 'method' => 'OAuth']);
        }
        GoogleTagManager::flashPush(['event' => 'login', 'method' => 'OAuth']);
    
        return redirect()->intended();
    }
    GoogleTagManager::flashPush(['event' => 'sign_up', 'method' => 'OAuth']);
  10. Use dump() to convert arrays to JSON for data attributes

    main

    The dump() method converts an array into a JSON object string. This is useful for passing data from PHP to JavaScript via HTML data attributes.

    <a data-gtm-product='{!! GoogleTagManager::dump($product->toArray()) !!}' data-gtm-click>Product</a>
    <a data-gtm-product='{!! GoogleTagManager::dump($product->toArray()) !!}' data-gtm-click>Product</a>
  11. Add data to the DataLayer using set()

    main

    Use GoogleTagManager::set() to add data to the dataLayer. This data is rendered automatically. Setting new values merges them with existing ones. The method supports dot notation for nested arrays.

    // Set a simple key-value pair
    GoogleTagManager::set('pageType', 'productDetail');
    
    // Set an array
    GoogleTagManager::set(['foo' => 'bar']);
    
    // Set nested data using dot notation
    GoogleTagManager::set('baz.ho', 'doorrrrr');
    GoogleTagManager::set('pageType', 'productDetail');
  12. Configure the Google Tag Manager session key

    main

    The GoogleTagManagerMiddleware uses a session key to persist data between requests. This key is retrieved from the googletagmanager.sessionKey configuration value. By default, this determines where the middleware looks for and stores data intended for the Google Tag Manager DataLayer during the request lifecycle.

    // The middleware looks for this key in your config/googletagmanager.php
    'sessionKey' => 'googletagmanager_session_key',