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
Requires
- php: ^8.2
- illuminate/support: ^10.0|^11.0|^12.0
Requires (Dev)
- laravel/pint: ^1.26
- orchestra/testbench: ^8.0|^9.0|^10.9
- phpstan/phpstan: ^1.12
- phpunit/phpunit: ^10.0|^11.5
Suggests
- livewire/livewire: Enables automatic Single Page Application (SPA) navigation tracking for Livewire applications
This package is auto-updated.
Last update: 2026-01-20 15:34:17 UTC
README
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:
- Go to Google Analytics
- Navigate to Admin โ Data Streams โ [Your Stream]
- 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
- Automatic Detection: The package checks if
Livewire\Livewireclass exists - Event Listening: Listens to
livewire:navigatedevents - Page View Tracking: Sends GA4
page_viewevents on navigation - 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:
- Check
.envhasGA4_MEASUREMENT_IDset - Verify ID format:
G-XXXXXXXXXX - Clear config cache:
php artisan config:clear - Check if measurement ID is empty or invalid
Livewire Navigation Not Tracked
Symptoms: Page views only on full reloads
Solutions:
- Install Livewire:
composer require livewire/livewire - Verify Livewire is properly installed
- Check browser console for JavaScript errors
JavaScript Errors
Symptoms: Console shows GA4-related errors
Solutions:
- Verify measurement ID is valid
- Check for typos in ID
- Ensure ID starts with "G-"
- Check network tab for failed script loads
Double Page Views
Symptoms: Duplicate page_view events in GA4
Solutions:
- Package disables auto
page_viewby default - Check for manual
gtag('config')calls in your code - 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
- Never Commit Sensitive Data:
# Add to .gitignore .env .env.local .env.*.local
- 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
- 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
- GitHub Issues: Report bugs or request features
- GitHub Discussions: Ask questions and share ideas
- Documentation: This README and source code comments
Contributing
Contributions are welcome! Please:
- Fork the repository
- Create a feature branch
- Make your changes
- Add tests for new functionality
- Ensure all tests pass
- 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