ronald2wing/laravel-ga4

A lightweight Laravel package for seamless Google Analytics 4 (GA4) integration with automatic Livewire SPA navigation tracking, Blade directives, and secure JavaScript injection

Fund package maintenance!
ronald2wing
Other

Installs: 46

Dependents: 0

Suggesters: 0

Security: 0

Stars: 0

Watchers: 0

Forks: 0

pkg:composer/ronald2wing/laravel-ga4

1.0.0 2026-01-20 15:31 UTC

This package is auto-updated.

Last update: 2026-01-20 15:34:17 UTC


README

Latest Version on Packagist Total Downloads License PHP Version Test Coverage GitHub Actions

A lightweight Laravel package for seamless Google Analytics 4 (GA4) integration with automatic Livewire SPA navigation tracking, Blade directives, and secure JavaScript injection.

โœจ Key Features

  • ๐Ÿš€ One-line Integration โ€“ Add GA4 tracking with {!! ga4() !!} in Blade templates
  • โšก Livewire SPA Support โ€“ Automatic detection and tracking for Livewire applications
  • ๐Ÿ”’ Secure JavaScript Injection โ€“ Proper HTML escaping and safe script generation
  • ๐ŸŒ Environment Aware โ€“ Only renders when measurement ID is configured
  • ๐ŸŽฏ Disabled Auto Page Views โ€“ Better control over when page views are tracked
  • โš™๏ธ Zero Configuration โ€“ Works with sensible defaults out of the box
  • ๐Ÿงช 100% Test Coverage โ€“ Comprehensive test suite with edge cases
  • ๐Ÿ”„ Laravel 10-12 Support โ€“ Compatible with modern Laravel versions
  • ๐Ÿ“ฆ Publishable Configuration โ€“ Customize settings when needed

๐Ÿ“‹ Requirements

  • PHP: 8.2 or higher
  • Laravel: 10.x, 11.x, or 12.x
  • Composer: Latest version recommended

Optional Dependencies

  • Livewire: For SPA navigation tracking (auto-detected)

๐Ÿš€ Quick Start

1. Installation

Install the package via Composer:

composer require ronald2wing/laravel-ga4

The package will automatically register its service provider and facade.

2. Configuration

Add your GA4 Measurement ID to your .env file:

GA4_MEASUREMENT_ID=G-XXXXXXXXXX

How to find your Measurement ID:

  1. Go to Google Analytics
  2. Navigate to Admin โ†’ Data Streams โ†’ [Your Stream]
  3. Copy the Measurement ID (starts with "G-")

3. Usage in Blade Templates

Add the tracking script to your Blade layout:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Your Application</title>
</head>
<body>
    <!-- Your application content -->

    <!-- Add GA4 tracking before closing body tag -->
    {!! ga4() !!}
</body>
</html>

โš™๏ธ Configuration

Environment Configuration

The package uses a single environment variable:

GA4_MEASUREMENT_ID=G-XXXXXXXXXX

Configuration File

Publish the configuration file to customize settings:

php artisan vendor:publish --tag=ga4-config

This creates config/ga4.php:

return [
    /*
    |--------------------------------------------------------------------------
    | Google Analytics 4 Measurement ID
    |--------------------------------------------------------------------------
    |
    | Your GA4 measurement ID (format: G-XXXXXXXXXX).
    |
    */
    'measurement_id' => env('GA4_MEASUREMENT_ID', ''),
];

๐Ÿ“– Usage Guide

Basic Usage

The simplest way to use the package is with the ga4() helper function:

<!-- In any Blade template, typically in your layout file -->
{!! ga4() !!}

Programmatic Access

You can also access the GA4 service programmatically using the facade:

use Ronald2Wing\LaravelGa4\Facades\Ga4;

// Get the rendered script
$script = Ga4::render();

// Check if GA4 is configured
if (Ga4::render() !== '') {
    // GA4 is active and ready
}

Conditional Rendering Examples

<!-- Only render in production environment -->
@if(app()->environment('production'))
    {!! ga4() !!}
@endif

<!-- Only render for authenticated users -->
@auth
    {!! ga4() !!}
@endauth

<!-- Only render when measurement ID is set -->
@if(config('ga4.measurement_id'))
    {!! ga4() !!}
@endif

<!-- Combine multiple conditions -->
@if(app()->environment('production') && config('ga4.measurement_id'))
    {!! ga4() !!}
@endif

โšก Livewire Integration

Automatic SPA Navigation Tracking

When Livewire is installed, the package automatically adds SPA navigation tracking. This means page views are tracked when users navigate between Livewire components without full page reloads.

How It Works

  1. Automatic Detection: The package checks if Livewire\Livewire class exists
  2. Event Listening: Listens to livewire:navigated events
  3. Page View Tracking: Sends GA4 page_view events on navigation
  4. No Configuration Needed: Works automatically when Livewire is installed

Installing Livewire

composer require livewire/livewire

Note: Livewire is optional. The package works perfectly without it, but SPA navigation tracking won't be available.

๐Ÿ”ง Advanced Usage

Custom JavaScript Integration

If you need to integrate with custom JavaScript, you can access the generated script:

use Ronald2Wing\LaravelGa4\Facades\Ga4;

// Get the raw JavaScript (without script tags)
$service = app('ga4');
$measurementId = config('ga4.measurement_id');

// Or use the facade to get complete HTML
$html = Ga4::render();

Multiple Environments Setup

For different environments, use different measurement IDs:

# Development (optional - can be empty)
GA4_MEASUREMENT_ID=

# Staging
GA4_MEASUREMENT_ID=G-STG123456

# Production
GA4_MEASUREMENT_ID=G-PRO123456

๐Ÿ› Troubleshooting

Common Issues & Solutions

Script Not Rendering

Symptoms: No GA4 script in HTML output

Solutions:

  1. Check .env has GA4_MEASUREMENT_ID set
  2. Verify ID format: G-XXXXXXXXXX
  3. Clear config cache: php artisan config:clear
  4. Check if measurement ID is empty or invalid

Livewire Navigation Not Tracked

Symptoms: Page views only on full reloads

Solutions:

  1. Install Livewire: composer require livewire/livewire
  2. Verify Livewire is properly installed
  3. Check browser console for JavaScript errors

JavaScript Errors

Symptoms: Console shows GA4-related errors

Solutions:

  1. Verify measurement ID is valid
  2. Check for typos in ID
  3. Ensure ID starts with "G-"
  4. Check network tab for failed script loads

Double Page Views

Symptoms: Duplicate page_view events in GA4

Solutions:

  1. Package disables auto page_view by default
  2. Check for manual gtag('config') calls in your code
  3. Verify no other GA4 scripts are loaded

๐Ÿ”’ Security

Security Features

  • HTML Escaping: All output is properly escaped using htmlspecialchars()
  • JavaScript Safety: Measurement ID is JSON-encoded with hex encoding
  • Input Validation: Measurement ID is validated as non-empty string
  • No Sensitive Data: Only measurement ID is exposed in output

Best Practices

  1. Never Commit Sensitive Data:
# Add to .gitignore
.env
.env.local
.env.*.local
  1. Use Different IDs Per Environment:
# Development (optional - can be empty)
GA4_MEASUREMENT_ID=

# Staging
GA4_MEASUREMENT_ID=G-STG123456

# Production
GA4_MEASUREMENT_ID=G-PRO123456
  1. Regular Security Updates:
# Check for vulnerabilities
composer audit

# Update dependencies
composer update

๐Ÿงช Testing

Running Tests

# Run all tests
composer test

# Generate HTML coverage report
composer test-coverage

# Run tests with verbose output
composer test-verbose

# Run specific test method(s)
composer test-filter testRenderReturnsEmptyStringWhenNotConfigured

# Static analysis with PHPStan
composer analyse

# Check code style (dry run)
composer lint

# Fix code style issues
composer pint

Test Coverage

The package maintains 100% test coverage with:

  • 118 tests
  • 286 assertions
  • Comprehensive edge case coverage
  • Livewire integration tests
  • Configuration validation tests

๐Ÿ› ๏ธ Development

Development Commands

# Install dependencies
composer install

# Run full test suite with linting check
composer check

# Update dependencies
composer update

# Check for outdated packages
composer outdated

# Check for security vulnerabilities
composer audit

# Generate coverage report (HTML)
composer test-coverage

# Run tests with verbose output
composer test-verbose

# Fix code style issues with Pint
composer pint

# Static analysis with PHPStan
composer analyse

๐Ÿ“ฆ Dependencies

Required Dependencies

  • PHP: ^8.2 (8.2 or higher)
  • illuminate/support: ^10.0|^11.0|^12.0 (Laravel 10-12 compatible)

Development Dependencies

  • orchestra/testbench: ^8.0|^9.0|^10.9 (Laravel package testing)
  • phpunit/phpunit: ^10.0|^11.5 (testing framework)
  • laravel/pint: ^1.26 (code style fixing)
  • phpstan/phpstan: ^1.12 (static analysis)

Suggested Dependencies

  • livewire/livewire: For SPA navigation tracking (auto-detected)

๐Ÿ“„ License

This package is open-sourced software licensed under the MIT license.

๐Ÿค Support

Getting Help

Contributing

Contributions are welcome! Please:

  1. Fork the repository
  2. Create a feature branch
  3. Make your changes
  4. Add tests for new functionality
  5. Ensure all tests pass
  6. Submit a pull request

Made with โค๏ธ by Ronald2Wing

If you find this package useful, please consider:

  • โญ Starring the repository on GitHub
  • ๐Ÿ› Reporting issues to help improve the package
  • ๐Ÿ’– Sponsoring the developer on GitHub Sponsors