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

Laravel4 Googletagmanager Laravel Package

spatie/laravel4-googletagmanager

Abandoned Laravel 4 package for integrating Google Tag Manager. Provides a facade/service provider to manage the GTM dataLayer and include the container code in your app. For Laravel 5+, use spatie/laravel-googletagmanager.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation (if still needed for legacy projects):

    composer require spatie/laravel4-googletagmanager
    

    Note: This package is abandoned and only works with Laravel 4. For new projects, use spatie/laravel-googletagmanager for Laravel 5+.

  2. Publish Config:

    php artisan config:publish spatie/googletagmanager
    

    Update .env with your GTM ID:

    GTM_ID=GTM-XXXXXX
    
  3. Add to Layout: In your master Blade template (e.g., resources/views/layouts/app.blade.php), include the GTM snippet:

    @include('googletagmanager::gtm')
    
  4. First Use Case: Push a basic event to the dataLayer in a controller or service:

    use Spatie\GoogleTagManager\GoogleTagManager;
    
    GoogleTagManager::push([
        'event' => 'page_view',
        'page' => 'home',
    ]);
    

Implementation Patterns

Core Workflows

  1. Data Layer Management:

    • Push structured data to dataLayer for GTM triggers:
      // Track a custom event
      GoogleTagManager::push([
          'event' => 'product_view',
          'product_id' => $product->id,
          'price' => $product->price,
      ]);
      
    • Use helper methods for common events:
      GoogleTagManager::trackPageView('/products/123');
      GoogleTagManager::trackEvent('checkout_started', ['value' => 99.99]);
      
  2. Conditional Loading: Disable GTM in specific environments (e.g., staging) via config:

    // config/googletagmanager.php
    'enabled' => env('APP_ENV') !== 'staging',
    
  3. Dynamic Data Injection: Attach user or session data to every page view:

    // In a middleware or service provider
    GoogleTagManager::push([
        'user_id' => auth()->id(),
        'user_email' => auth()->user()->email,
    ]);
    
  4. E-Commerce Tracking: Use the package’s built-in e-commerce helpers:

    GoogleTagManager::trackEcommercePurchase([
        'transaction_id' => 'T12345',
        'affiliation' => 'Summer Sale',
        'revenue' => '35.99',
        'tax' => '3.19',
        'shipping' => '5.00',
        'products' => [
            ['name' => 'Widget', 'id' => 'P123', 'price' => '19.99', 'quantity' => 1],
        ],
    ]);
    
  5. Blade Directives: Push data directly in Blade templates:

    @gtmPush({
        'event': 'video_play',
        'video_id': '{{ $video->id }}',
        'duration': '{{ $video->duration }}'
    })
    

Gotchas and Tips

Pitfalls

  1. Laravel 4 Only:

    • This package will not work with Laravel 5+. Use spatie/laravel-googletagmanager instead.
    • If migrating from Laravel 4, manually extract the GTM logic or rewrite using the newer package.
  2. Data Layer Timing:

    • Ensure dataLayer pushes occur before the GTM snippet loads. In Blade, place @include('googletagmanager::gtm') at the end of <body> and push data earlier in the template.
  3. Caching Issues:

    • If GTM events aren’t firing, clear Laravel’s view cache:
      php artisan view:clear
      
  4. Environment-Specific IDs:

    • Avoid hardcoding GTM IDs in Blade. Use the config:
      <!-- Wrong: -->
      <script>dataLayer = [{'gtm.id': 'GTM-XXXXXX'}];</script>
      
      <!-- Correct: -->
      @include('googletagmanager::gtm')
      

Debugging

  1. Verify dataLayer: Inspect the browser console to confirm data is being pushed:

    console.log(window.dataLayer);
    

    Expected output:

    [
        {"event":"page_view","page":"home"},
        {"event":"product_view","product_id":123}
    ]
    
  2. GTM Preview Mode: Use GTM’s Preview Mode to test events without publishing.

  3. Log Missing Events: Add a middleware to log dataLayer pushes for debugging:

    // app/Http/Middleware/LogGtmEvents.php
    public function handle($request, Closure $next) {
        if (GoogleTagManager::hasPushedData()) {
            Log::debug('GTM Events:', GoogleTagManager::getPushedData());
        }
        return $next($request);
    }
    

Extension Points

  1. Custom Data Layer Initialization: Override the default dataLayer initialization in app/Providers/AppServiceProvider.php:

    public function boot() {
        GoogleTagManager::initialize([
            'dataLayer' => ['custom' => 'value'],
        ]);
    }
    
  2. Event Macros: Extend the package with custom event types:

    // app/Providers/GoogleTagManagerServiceProvider.php
    public function boot() {
        GoogleTagManager::macro('trackFormSubmit', function ($formName, $data = []) {
            $this->push(array_merge([
                'event' => 'form_submit',
                'form' => $formName,
            ], $data));
        });
    }
    

    Usage:

    GoogleTagManager::trackFormSubmit('contact', ['success' => true]);
    
  3. Async Loading: For better performance, load GTM asynchronously:

    <!-- resources/views/layouts/app.blade.php -->
    @if(config('googletagmanager.enabled'))
        <noscript><iframe src="//www.googletagmanager.com/ns.html?id={{ config('googletagmanager.id') }}"
          height="0" width="0" style="display:none;visibility:hidden"></iframe></noscript>
        <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','{{ config('googletagmanager.id') }}');</script>
    @endif
    
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