PHPackages                             straylightagency/datalayer - 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. [Utility &amp; Helpers](/categories/utility)
4. /
5. straylightagency/datalayer

ActiveLibrary[Utility &amp; Helpers](/categories/utility)

straylightagency/datalayer
==========================

A helper package that help to generate Google's DataLayer script on pages

011PHP

Since May 26Pushed 1mo agoCompare

[ Source](https://github.com/straylightagency/php-datalayer)[ Packagist](https://packagist.org/packages/straylightagency/datalayer)[ RSS](/packages/straylightagency-datalayer/feed)WikiDiscussions main Synced 1w ago

READMEChangelogDependenciesVersions (1)Used By (0)

PHP DataLayer Manager
=====================

[](#php-datalayer-manager)

A helper package that help to generate Google's DataLayer script on pages.

Data can be stored in session, like in a conversion funnel process, and be printed on the last page before being cleared.

Installation
------------

[](#installation)

Require this package with composer.

```
composer require straylightagency/datalayer
```

### Laravel without auto-discovery:

[](#laravel-without-auto-discovery)

If you do not use auto-discovery, add the ServiceProvider to the providers array in `bootstrap/providers.php` :

```
\Straylightagency\DataLayer\Laravel\DataLayerServiceProvider::class,
```

Finally, add your GTM-ID in your `.env` file :

```
GOOGLE_TAG_MANAGER_ID="GTM-XXXXXXXX"
```

Usage
-----

[](#usage)

### Without Laravel

[](#without-laravel)

You must create a SessionHandler object. Handler uses session to pass data through pages. Then you can pass the SessionHandler to the DataLayerHandler using the constructor :

```
use Straylightagency\DataLayer\DataLayerManager;
use Straylightagency\DataLayer\SessionHandler;

$datalayer = new DataLayerManager(
                new SessionHandler, 'GTM-XXXXXXXX'
            );
```

A static method is available to create a new instance using the basic session handler

```
use Straylightagency\DataLayer\DataLayerManager;

$datalayer = DataLayerManager::newUsingBasicSession('GTM-XXXXXXXX');
```

### With Laravel

[](#with-laravel)

The package handles initialization and configuration from the service provider.

You can call methods from `DataLayerManager` directly using the Facade `DataLayer` or use the alias instead.

```
use Straylightagency\DataLayer\Laravel\DataLayer;

DataLayer::with('foo', 'bar');
```

API documentation
-----------------

[](#api-documentation)

Examples bellow are using Laravel Facade `DataLayer`.

### In your controllers

[](#in-your-controllers)

#### Set one value in the DataLayer

[](#set-one-value-in-the-datalayer)

```
DataLayer::with('foo', 'bar');
```

#### Set an array of data in the DataLayer

[](#set-an-array-of-data-in-the-datalayer)

```
DataLayer::withArray( [
    'user_name' => 'John Doe',
    'age' => '42',
    'country' => 'Belgium',
] );
```

Both methods can be chained :

```
DataLayer::with('foo', 'bar')
        ->withArray( [
            'user_name' => 'John Doe',
            'age' => '42',
            'country' => 'Belgium',
        ] )
        ->with('name', 'value');
```

Do not hesitate to check the prototype of the method to view all possibles options.

### In your views

[](#in-your-views)

#### Publish the DataLayer in the view

[](#publish-the-datalayer-in-the-view)

Just call this method in your app layout before the closing `` tag.

```
DataLayer::print();
```

It will print this entire HTML code in your layout :

```

    dataLayer = dataLayer || [];

    dataLayer.push({foo:'bar',user_name:'John Doe',age:42,country:'Belgium'});

(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=
'//www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);
})(window,document,'script','dataLayer','GTM-XXXXXXXX');

```

Do not forget to call `DataLayer::printNoScript()` right after your `` tag :

```
DataLayer::printNoScript();
```

It will print the following :

```

```

You can use named parameters to choose if you do not want to initialise the global JS object, initialise the Google Tag Manager script or to clear data after publish.

```
DataLayer::print(
    init: false,
    clear: false,
    script: false,
);
```

It will just print this :

```

    dataLayer.push({foo:'bar',user_name:'John Doe',age:42,country:'Belgium'});

```

#### Push an array of data in the DataLayer

[](#push-an-array-of-data-in-the-datalayer)

```
DataLayer::pushData( [
    'user_name' => 'John Doe',
    'age' => '42',
    'country' => 'Belgium',
], [clear: bool = false] );
```

### Others methods

[](#others-methods)

#### Load the data from session

[](#load-the-data-from-session)

```
DataLayer::load();
```

#### Save the data in the session

[](#save-the-data-in-the-session)

```
DataLayer::save();
```

#### Clear the data in the session

[](#clear-the-data-in-the-session)

```
DataLayer::clear();
```

#### Get the array data

[](#get-the-array-data)

```
$data = DataLayer::getData();
$data = DataLayer::data(); # alias of the getData method
```

#### Print the global JS object in the view

[](#print-the-global-js-object-in-the-view)

```
echo DataLayer::init();
```

It will print this in the HTML :

```

    window.dataLayer = window.dataLayer || [];

```

#### Print the Google Tag Manager script in the view

[](#print-the-google-tag-manager-script-in-the-view)

The `$gtm_id` parameter is optional. If omitted, it will use the Google ID set in your .env file.

```
echo DataLayer::script([gtm_id: null|string = null]);
```

```

(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=
'//www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);
})(window,document,'script','dataLayer','GTM-XXXXXXXX');

```

Also, do not forget to add the `` tag with noScript :

```
echo DataLayer::noScript([gtm_id: null|string = null]);
```

... or use printNoScript :

```
DataLayer::printNoScript([gtm_id: null|string = null]);
```

```

```

#### Show the content of the DataLayer (debug purpose)

[](#show-the-content-of-the-datalayer-debug-purpose)

```
DataLayer::dump();
```

### Requirement

[](#requirement)

PHP 8.3 or above

See also
--------

[](#see-also)

- [Dev Guide](https://developers.google.com/tag-manager/devguide)
- [Quick Start](https://developers.google.com/tag-manager/quickstart)

Credits
-------

[](#credits)

- [Anthony Pauwels](https://github.com/anthonypauwels)
- [All Contributors](../../contributors)

License
-------

[](#license)

The MIT License (MIT).

###  Health Score

21

—

LowBetter than 17% of packages

Maintenance58

Moderate activity, may be stable

Popularity6

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity11

Early-stage or recently created project

 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.

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/4163238?v=4)[Anthony Pauwels](/maintainers/anthonypauwels)[@anthonypauwels](https://github.com/anthonypauwels)

---

Top Contributors

[![anthonypauwels](https://avatars.githubusercontent.com/u/4163238?v=4)](https://github.com/anthonypauwels "anthonypauwels (13 commits)")

### Embed Badge

![Health badge](/badges/straylightagency-datalayer/health.svg)

```
[![Health](https://phpackages.com/badges/straylightagency-datalayer/health.svg)](https://phpackages.com/packages/straylightagency-datalayer)
```

###  Alternatives

[gabrielrcouto/php-gui

Extensionless PHP Graphic User Interface library

2.2k7.5k](/packages/gabrielrcouto-php-gui)[dcblogdev/laravel-junie

Install pre-configured guides for Jetbrains Junie

383.5k](/packages/dcblogdev-laravel-junie)

PHPackages © 2026

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