ronald2wing / laravel-ga4
Laravel package for Google Analytics 4 (GA4) tracking with automatic Livewire SPA support
Fund package maintenance!
ronald2wing
Installs: 14
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
- phpunit/phpunit: ^10.0
Suggests
- livewire/livewire: Required for automatic Single Page Application (SPA) navigation tracking in Livewire applications
This package is auto-updated.
Last update: 2025-12-25 18:57:28 UTC
README
A Laravel package for seamless Google Analytics 4 (GA4) integration with automatic Livewire SPA navigation tracking.
๐ Quick Installation
composer require ronald2wing/laravel-ga4
Add your GA4 Measurement ID to .env:
GA4_MEASUREMENT_ID=G-XXXXXXXXXX
Add to your Blade layout:
{!! ga4() !!}
๐ Table of Contents
- โจ Features
- ๐ Requirements
- ๐ Quick Start
- ๐ Usage
- โก Livewire Integration
- โ๏ธ Configuration
- ๐ง Troubleshooting
- ๐งช Testing
- ๐ฆ Dependencies
- ๐ License
โจ Why This Package?
Integrating Google Analytics 4 into Laravel applications can be tedious, especially when dealing with manual script injection, SPA navigation tracking for Livewire applications, and environment-specific configuration.
This package solves these problems with a simple, elegant API that "just works".
๐ Key Features
- Automatic GA4 Script Injection โ Single line of code in your Blade templates
- Livewire SPA Detection โ Automatically detects and integrates with Livewire
- Environment-Aware โ Only renders when properly configured
- Security First โ Proper HTML escaping and safe JavaScript injection
- Performance Optimized โ Minimal overhead, no database queries
- SPA Navigation Tracking โ Automatic page view tracking for Livewire applications
- Disabled Auto Page Views โ Better control over when page views are tracked
- Configurable โ Publishable configuration for customization
- Full Test Coverage โ Comprehensive unit tests with edge cases
๐ Requirements
- PHP: ^8.2 (8.2 or higher)
- Laravel: ^10.x|^11.x|^12.x
- Composer: Latest version recommended
Optional Dependencies
- Livewire: For SPA navigation tracking (auto-detected)
๐ Quick Start
1. Install the Package
composer require ronald2wing/laravel-ga4
2. Configure Your GA4 Measurement ID
Add your GA4 Measurement ID to your .env file:
GA4_MEASUREMENT_ID=G-XXXXXXXXXX
Where to find your Measurement ID:
- Go to Google Analytics
- Navigate to Admin โ Data Streams โ [Your Stream]
- Copy the Measurement ID (starts with "G-")
3. Add to Your Layout
In your main layout file (typically resources/views/layouts/app.blade.php), add the GA4 script before the closing </body> tag:
<!DOCTYPE html> <html lang="{{ str_replace('_', '-', app()->getLocale()) }}"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>@yield('title', config('app.name'))</title> @vite(['resources/css/app.css', 'resources/js/app.js']) </head> <body> @yield('content') <!-- Add GA4 tracking script --> {!! ga4() !!} </body> </html>
That's it! Your GA4 tracking is now live.
๐ Detailed Usage
Basic Usage in Blade Templates
The simplest way to use the package is with the ga4() helper function:
<!-- In any Blade template --> {!! 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
@if(app()->environment('production')) {!! 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_view events on navigation
Installing Livewire
composer require livewire/livewire
Note: Livewire is optional. The package works perfectly without it, but SPA navigation tracking won't be available.
โ๏ธ Configuration
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', ''), ];
Environment Variables
The package uses a single environment variable:
# Required for GA4 tracking GA4_MEASUREMENT_ID=G-XXXXXXXXXX
๐ง Troubleshooting
Common Issues & Solutions
Script not rendering
- Symptoms: No GA4 script in HTML output
- Solution:
- Check
.envhasGA4_MEASUREMENT_ID - Verify ID format:
G-XXXXXXXXXX - Clear config cache:
php artisan config:clear
- Check
Livewire navigation not tracked
- Symptoms: Page views only on full reloads
- Solution:
- Install Livewire:
composer require livewire/livewire - Verify Livewire is properly installed
- Install Livewire:
JavaScript errors
- Symptoms: Console shows GA4-related errors
- Solution:
- Verify measurement ID is valid
- Check for typos in ID
- Ensure ID starts with "G-"
Double page views
- Symptoms: Duplicate page_view events in GA4
- Solution:
- Package disables auto page_view
- Check for manual
gtag('config')calls
Debugging Steps
-
Check Configuration:
php artisan tinker >>> config('ga4.measurement_id') -
Verify Script Generation:
php artisan tinker >>> ga4()
๐ก๏ธ Security Best Practices
1. Never Commit Sensitive Data
# Add to .gitignore .env .env.local .env.*.local
2. Use Different IDs Per Environment
# Development (optional - can be empty) GA4_MEASUREMENT_ID_DEVELOPMENT= # Staging GA4_MEASUREMENT_ID_STAGING=G-STG123456 # Production GA4_MEASUREMENT_ID_PRODUCTION=G-PRO123456
3. Regular Security Updates
# Check for vulnerabilities composer audit # Update dependencies composer update
โก Performance Considerations
Minimal Overhead
- No Database Queries: Configuration is loaded from memory
- No External API Calls: Script generation is purely local
- Single Generation: Script is generated once per request when called
- Caching Friendly: Works with Laravel's caching mechanisms
๐งช Testing
Running Tests
# Run all tests composer test # Generate coverage report (HTML) composer test-coverage # Run tests with verbose output composer test-verbose # Run specific test method(s) by name pattern(s) composer test-filter testRenderReturnsEmptyStringWhenNotConfigured # Static analysis with PHPStan (max level) composer analyze # Lint all PHP files composer lint-all # Combined check (lint + test) composer check
Test Coverage
The package has 100% test coverage. Coverage reports are generated in the coverage/ directory.
Test Suite Structure
The package includes comprehensive unit tests covering:
- Configuration validation
- Livewire integration
- Edge cases
- Service provider registration
- Facade access
- Helper functions
๐ ๏ธ 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 # Run all tests composer test # Generate coverage report (HTML) composer test-coverage # Run tests with verbose output composer test-verbose # Run specific test method(s) by name pattern(s) composer test-filter testRenderReturnsEmptyStringWhenNotConfigured # Lint all PHP files (syntax check) composer lint-all # Check code style with Pint (dry run) composer pint-test # Fix code style issues with Pint composer pint-fix # Run Pint composer pint # Static analysis with PHPStan (max level) composer analyze
Project Structure
laravel-ga4/
โโโ config/
โ โโโ ga4.php # Package configuration
โโโ src/
โ โโโ Facades/
โ โ โโโ Ga4.php # Facade for service access
โ โโโ Ga4Service.php # Core service class
โ โโโ Ga4ServiceProvider.php # Service provider
โ โโโ helpers.php # Helper functions
โโโ tests/
โ โโโ Unit/ # Comprehensive test suite
โโโ composer.json # Package definition
โโโ README.md # This file
๐ Version Compatibility
| Laravel Version | Package Compatibility | PHP Version |
|---|---|---|
| 10.x | โ Fully Supported | ^8.2 |
| 11.x | โ Fully Supported | ^8.2 |
| 12.x | โ Fully Supported | ^8.2 |
๐ฆ Dependencies
Required Dependencies
- PHP: ^8.2
- illuminate/support: ^10.0|^11.0|^12.0
Development Dependencies
- orchestra/testbench: ^8.0
- phpunit/phpunit: ^10.0
- laravel/pint: ^1.26
Suggested Dependencies
- livewire/livewire: For SPA navigation tracking
๐ License
This package is open-sourced software licensed under the MIT license.
๐ค Support
Getting Help
- GitHub Issues: Report bugs or request features
- Documentation: This README and source code comments
Reporting Issues
When reporting issues, please include:
- Laravel version
- Package version
- PHP version
- Error messages or logs
- Steps to reproduce
๐ Changelog
All notable changes to this project will be documented in this section.
[1.0.0] - 2025-12-24
Added
- Initial release with core GA4 tracking functionality
- Automatic Livewire SPA navigation tracking detection
- Comprehensive test suite with 100% coverage
- Configuration file with environment variable support
- Helper function
ga4()for easy Blade integration - Facade
Ga4::render()for programmatic access
For a detailed view of all changes, see the GitHub commit history and CHANGELOG.md.
๐ Additional Resources
Made with โค๏ธ by Ronald2Wing
If this package saves you time, please consider โญ starring the repository!