PHPackages                             ronald2wing/laravel-ga4 - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Templating &amp; Views](/categories/templating)
4. /
5. ronald2wing/laravel-ga4

ActiveLibrary[Templating &amp; Views](/categories/templating)

ronald2wing/laravel-ga4
=======================

A lightweight Laravel package for seamless Google Analytics 4 (GA4) integration with Blade directives and secure JavaScript injection

1.1.0(1mo ago)0135MITPHPPHP ^8.3CI passing

Since Mar 5Pushed 1mo agoCompare

[ Source](https://github.com/ronald2wing/Laravel-GA4)[ Packagist](https://packagist.org/packages/ronald2wing/laravel-ga4)[ Docs](https://github.com/ronald2wing/laravel-ga4)[ GitHub Sponsors](https://github.com/sponsors/ronald2wing)[ Fund](https://www.buymeacoffee.com/ronald2wing)[ RSS](/packages/ronald2wing-laravel-ga4/feed)WikiDiscussions master Synced 1mo ago

READMEChangelog (2)Dependencies (10)Versions (3)Used By (0)

Laravel GA4
===========

[](#laravel-ga4)

[![Latest Version on Packagist](https://camo.githubusercontent.com/891323ccd990cb25581692d3e8fe1233c8ad1636c37a69b2a30a910796e9464a/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f726f6e616c643277696e672f6c61726176656c2d6761342e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/ronald2wing/laravel-ga4)[![Total Downloads](https://camo.githubusercontent.com/3d85637ee3e5fc7e0442f3a6dfe63d07d1b36470f3cc7a856da21b0976e67bde/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f726f6e616c643277696e672f6c61726176656c2d6761342e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/ronald2wing/laravel-ga4)[![License](https://camo.githubusercontent.com/fa6697c2138647f21c69511fada60ad295036b23d6023ce79b23d4a416b2c54e/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f6c2f726f6e616c643277696e672f6c61726176656c2d6761342e7376673f7374796c653d666c61742d737175617265)](LICENSE)[![PHP Version](https://camo.githubusercontent.com/224fcdea48d563c1cf653b3385df282eba11c5e7f39c46fcb3c3e189906c8cd3/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f7068702d762f726f6e616c643277696e672f6c61726176656c2d6761342e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/ronald2wing/laravel-ga4)[![Test Coverage](https://camo.githubusercontent.com/994d68acb2aadf1c3c7711ddcb3b30429246a6c05da9e601f62c3f932ac795a8/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f636f7665726167652d3130302532352d627269676874677265656e2e7376673f7374796c653d666c61742d737175617265)](https://github.com/ronald2wing/laravel-ga4)[![PHPStan](https://camo.githubusercontent.com/cfad767368c5b88c30d3a7087a14099cb45895b5ded11e2ae54aa298b7ba5893/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f5048505374616e2d6c6576656c2532306d61782d627269676874677265656e2e7376673f7374796c653d666c61742d737175617265)](https://github.com/ronald2wing/laravel-ga4)[![GitHub Actions](https://camo.githubusercontent.com/1db7f36f05fff697a515fc7b1232d9d8862dee38cff18c07515f64c0d4577aa2/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f726f6e616c643277696e672f6c61726176656c2d6761342f7068702e796d6c3f6272616e63683d6d6173746572267374796c653d666c61742d737175617265)](https://github.com/ronald2wing/laravel-ga4/actions)

A lightweight Laravel package for seamless Google Analytics 4 (GA4) integration with Blade directives and secure JavaScript injection.

✨ Features
----------

[](#-features)

- **One-line Integration** – Add GA4 tracking with `{!! ga4() !!}` in Blade templates
- **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
--------------

[](#-requirements)

- **PHP**: 8.3 or higher
- **Laravel**: 10.x, 11.x, 12.x, or 13.x
- **Composer**: Latest version recommended

🚀 Quick Start
-------------

[](#-quick-start)

### 1. Installation

[](#1-installation)

```
composer require ronald2wing/laravel-ga4
```

The package automatically registers its service provider and facade.

### 2. Configuration

[](#2-configuration)

Add your GA4 Measurement ID to `.env`:

```
GA4_MEASUREMENT_ID=G-XXXXXXXXXX
```

**How to find your Measurement ID:**

1. Go to [Google Analytics](https://analytics.google.com/)
2. Navigate to **Admin → Data Streams → \[Your Stream\]**
3. Copy the **Measurement ID** (starts with "G-")

### 3. Usage in Blade Templates

[](#3-usage-in-blade-templates)

Add the tracking script to your Blade layout:

```

    Your Application

    {!! ga4() !!}

```

⚙️ Configuration
----------------

[](#️-configuration)

### Environment Configuration

[](#environment-configuration)

The package uses a single environment variable:

```
GA4_MEASUREMENT_ID=G-XXXXXXXXXX
```

### Configuration File

[](#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
-------------

[](#-usage-guide)

### Basic Usage

[](#basic-usage)

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

```

{!! ga4() !!}
```

### Programmatic Access

[](#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

[](#conditional-rendering-examples)

```

@if(app()->environment('production'))
    {!! ga4() !!}
@endif

@auth
    {!! ga4() !!}
@endauth

@if(config('ga4.measurement_id'))
    {!! ga4() !!}
@endif

@if(app()->environment('production') && config('ga4.measurement_id'))
    {!! ga4() !!}
@endif
```

🔧 Advanced Usage
----------------

[](#-advanced-usage)

### Custom JavaScript Integration

[](#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

[](#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
-----------------

[](#-troubleshooting)

### Common Issues &amp; Solutions

[](#common-issues--solutions)

#### Script Not Rendering

[](#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

#### 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

[](#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)

### Security Features

[](#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

[](#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=

# Staging
GA4_MEASUREMENT_ID=G-STG123456

# Production
GA4_MEASUREMENT_ID=G-PRO123456
```

3. **Regular Security Updates**:

```
# Check for vulnerabilities
composer audit

# Update dependencies
composer update
```

🧪 Testing
---------

[](#-testing)

### Running Tests

[](#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

[](#test-coverage)

The package maintains **100% test coverage** with:

- **101 tests** (8 test files)
- **229 assertions**
- Comprehensive edge case coverage
- Configuration validation tests
- All tests passing with PHP 8.2-8.5 compatibility

🛠️ Development
--------------

[](#️-development)

### Development Commands

[](#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
--------------

[](#-dependencies)

### Required Dependencies

[](#required-dependencies)

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

### Development Dependencies

[](#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**: ^2.1.33 (static analysis)

### Suggested Dependencies

[](#suggested-dependencies)

- **None**: Package works standalone without any optional dependencies

📄 License
---------

[](#-license)

This package is open-sourced software licensed under the [MIT license](LICENSE).

🤝 Support
---------

[](#-support)

### Getting Help

[](#getting-help)

- **GitHub Issues**: [Report bugs or request features](https://github.com/ronald2wing/laravel-ga4/issues)
- **GitHub Discussions**: [Ask questions and share ideas](https://github.com/ronald2wing/laravel-ga4/discussions)
- **Documentation**: This README and source code comments

### Contributing

[](#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](https://github.com/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](https://github.com/sponsors/ronald2wing)

###  Health Score

42

—

FairBetter than 90% of packages

Maintenance89

Actively maintained with recent releases

Popularity13

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity50

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~14 days

Total

2

Last Release

54d ago

PHP version history (2 changes)1.0.0PHP ^8.2

1.1.0PHP ^8.3

### Community

Maintainers

![](https://www.gravatar.com/avatar/db229ddb4db3893dddd4793f880304c35a5e43c76e0b206acd546c07b51fc450?d=identicon)[ronald2wing](/maintainers/ronald2wing)

---

Top Contributors

[![ronald2wing](https://avatars.githubusercontent.com/u/16713673?v=4)](https://github.com/ronald2wing "ronald2wing (7 commits)")

---

Tags

analyticsga4google-analyticslaravellivewirephplaraveljavascriptlaravel-packagetrackingbladelivewireanalyticsgoogle-analyticsga4google analytics 4SPAsingle-page-application

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan

Code StyleLaravel Pint

Type Coverage Yes

### Embed Badge

![Health badge](/badges/ronald2wing-laravel-ga4/health.svg)

```
[![Health](https://phpackages.com/badges/ronald2wing-laravel-ga4/health.svg)](https://phpackages.com/packages/ronald2wing-laravel-ga4)
```

###  Alternatives

[robsontenorio/mary

Gorgeous UI components for Livewire powered by daisyUI and Tailwind

1.5k454.7k15](/packages/robsontenorio-mary)[bezhansalleh/filament-google-analytics

Google Analytics integration for FilamentPHP

205144.8k5](/packages/bezhansalleh-filament-google-analytics)[mati365/ckeditor5-livewire

CKEditor 5 integration for Laravel Livewire

413.9k](/packages/mati365-ckeditor5-livewire)[alexwestergaard/php-ga4

PHP Library for Google Analytics 4 with Server Side Tagging

63144.7k1](/packages/alexwestergaard-php-ga4)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
