Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Laravel Googletagmanager Laravel Package

spatie/laravel-googletagmanager

Laravel package for easy Google Tag Manager integration. Manage the JavaScript dataLayer from PHP, push variables and events, and include GTM scripts cleanly in your app with simple configuration and helpers.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require spatie/laravel-googletagmanager
    

    Publish the config file:

    php artisan vendor:publish --provider="Spatie\GoogleTagManager\GoogleTagManagerServiceProvider"
    
  2. Configuration: Edit .env to include your GTM ID:

    GOOGLE_TAG_MANAGER_ID=GTM-XXXXXX
    

    Or set it in config/googletagmanager.php:

    'id' => env('GOOGLE_TAG_MANAGER_ID', 'GTM-XXXXXX'),
    
  3. First Use Case: Add the GTM script to your layout (e.g., resources/views/layouts/app.blade.php):

    @googleTagManager
    

    This outputs the container snippet:

    <!-- Google Tag Manager -->
    <script>(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
    new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
    j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=
    'https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);
    })(window,document,'script','dataLayer','GTM-XXXXXX');</script>
    <!-- End Google Tag Manager -->
    

Implementation Patterns

Core Workflows

  1. Basic Tag Injection: Use the @googleTagManager directive in Blade views to inject the container snippet globally.

    @googleTagManager
    
  2. Conditional Tagging: Dynamically enable/disable GTM based on environment or user roles:

    if (app()->environment('production')) {
        echo \Spatie\GoogleTagManager\GoogleTagManager::container();
    }
    
  3. Event Tracking: Push dataLayer events from Laravel logic:

    use Spatie\GoogleTagManager\GoogleTagManager;
    
    // In a controller or service
    GoogleTagManager::push([
        'event' => 'user_registered',
        'user_id' => auth()->id(),
        'email' => auth()->user()->email,
    ]);
    
  4. Middleware Integration: Track page views or user actions via middleware:

    namespace App\Http\Middleware;
    
    use Closure;
    use Spatie\GoogleTagManager\GoogleTagManager;
    
    class TrackPageViews
    {
        public function handle($request, Closure $next)
        {
            GoogleTagManager::push([
                'event' => 'page_view',
                'page_url' => $request->url(),
                'page_title' => $request->route()->getName(),
            ]);
    
            return $next($request);
        }
    }
    
  5. View-Level Events: Trigger events in Blade templates:

    @googleTagManager([
        'event' => 'product_viewed',
        'product_id' => $product->id,
        'product_name' => $product->name,
    ])
    

Advanced Patterns

  1. Dynamic GTM ID: Override the GTM ID per request (e.g., for multi-tenant apps):

    config(['googletagmanager.id' => 'GTM-' . $tenant->gtm_id]);
    
  2. Custom Data Layer Structure: Extend the dataLayer array with custom properties:

    GoogleTagManager::push([
        'user' => [
            'id' => auth()->id(),
            'segment' => auth()->user()->segment,
        ],
        'custom_dimensions' => [
            'dimension1' => 'value1',
        ],
    ]);
    
  3. Server-Side Tagging (SST): Use the package to send server-side events to GTM (requires GTM Server-Side setup):

    GoogleTagManager::sendServerEvent([
        'event' => 'purchase',
        'transaction_id' => $order->id,
        'value' => $order->total,
    ]);
    
  4. Integration with Analytics: Combine with other Spatie packages (e.g., laravel-analytics) for unified tracking:

    use Spatie\Analytics\Analytics;
    use Spatie\GoogleTagManager\GoogleTagManager;
    
    Analytics::trackPageView();
    GoogleTagManager::push(['event' => 'page_view']);
    

Gotchas and Tips

Common Pitfalls

  1. Missing GTM ID:

    • Error: Blank or incorrect GTM ID causes no script to load.
    • Fix: Verify .env or config/googletagmanager.php has the correct GOOGLE_TAG_MANAGER_ID.
  2. Caching Issues:

    • Gotcha: Blade directives may not update if cached. Clear views:
      php artisan view:clear
      
    • Tip: Use @googleTagManager in uncached views or layouts.
  3. Data Layer Conflicts:

    • Gotcha: Multiple push() calls may overwrite dataLayer values.
    • Fix: Structure pushes logically (e.g., user data first, then events).
  4. Environment-Specific Tags:

    • Gotcha: GTM may load in development/staging, causing noise.
    • Fix: Use middleware or config checks:
      if (!app()->environment('local')) {
          echo \Spatie\GoogleTagManager\GoogleTagManager::container();
      }
      
  5. Async Script Blocking:

    • Gotcha: GTM script may delay page rendering if not async.
    • Fix: Ensure the package outputs the async script (default behavior).

Debugging Tips

  1. Verify Output: Inspect the rendered HTML to confirm the GTM snippet is present:

    <!-- Google Tag Manager -->
    <script>...</script>
    <!-- End Google Tag Manager -->
    
  2. Check DataLayer: Use browser DevTools (console.log(window.dataLayer)) to verify pushed events.

  3. GTM Preview Mode: Enable GTM’s preview mode to test events in real-time without publishing.

  4. Logging: Add debug logs for critical events:

    \Log::debug('GTM Event', [
        'event' => $eventData,
        'dataLayer' => \Spatie\GoogleTagManager\GoogleTagManager::getDataLayer(),
    ]);
    

Extension Points

  1. Custom Directives: Extend Blade directives for project-specific needs:

    // In AppServiceProvider@boot()
    Blade::directive('customGtm', function ($expression) {
        return "<?php echo \\Spatie\\GoogleTagManager\\GoogleTagManager::container($expression); ?>";
    });
    

    Usage:

    @customGtm(['custom' => 'value'])
    
  2. Override Container Method: Modify the container output in a service provider:

    // app/Providers/GoogleTagManagerServiceProvider.php
    public function boot()
    {
        \Spatie\GoogleTagManager\GoogleTagManager::macro('container', function ($options = []) {
            $html = \Spatie\GoogleTagManager\GoogleTagManager::getContainerHtml();
            return str_replace('GTM-XXXXXX', 'GTM-' . config('custom.gtm_id'), $html);
        });
    }
    
  3. Event Listeners: Trigger GTM events from Eloquent observers or Laravel events:

    // In UserObserver@created()
    \Spatie\GoogleTagManager\GoogleTagManager::push([
        'event' => 'user_created',
        'user_id' => $user->id,
    ]);
    
  4. Testing: Mock GTM in tests to avoid real requests:

    use Spatie\GoogleTagManager\GoogleTagManager;
    
    // In a test
    GoogleTagManager::shouldReceive('container')->andReturn('<script>mock</script>');
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
davejamesmiller/laravel-breadcrumbs
artisanry/parsedown
christhompsontldr/phpsdk
enqueue/dsn
bunny/bunny
enqueue/test
enqueue/null
enqueue/amqp-tools
milesj/emojibase
bower-asset/punycode
bower-asset/inputmask
bower-asset/jquery
bower-asset/yii2-pjax
laravel/nova
spatie/laravel-mailcoach
spatie/laravel-superseeder
laravel/liferaft
nst/json-test-suite
danielmiessler/sec-lists
jackalope/jackalope-transport