PHPackages                             josrom/laravel-analytics - 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. josrom/laravel-analytics

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

josrom/laravel-analytics
========================

Analytics tracking for Laravel

12.0.0(5mo ago)041MITPHPPHP ^8.2

Since Mar 27Pushed 5mo agoCompare

[ Source](https://github.com/JoseVte/laravel-analytics)[ Packagist](https://packagist.org/packages/josrom/laravel-analytics)[ RSS](/packages/josrom-laravel-analytics/feed)WikiDiscussions master Synced 1mo ago

READMEChangelogDependencies (4)Versions (38)Used By (0)

Analytics tracking package for Laravel
======================================

[](#analytics-tracking-package-for-laravel)

[![Latest Stable Version](https://camo.githubusercontent.com/bcee11cac52916fc60e006767a68a1ce0a64323c73b0c9fc1dc6b8ba8368a92f/68747470733a2f2f706f7365722e707567782e6f72672f6a6f73726f6d2f6c61726176656c2d616e616c79746963732f762f737461626c652e737667)](https://packagist.org/packages/josrom/laravel-analytics) [![Latest Unstable Version](https://camo.githubusercontent.com/28905bf035799870830b16a62897052e87fd6487005f51f508fbc064296eba33/68747470733a2f2f706f7365722e707567782e6f72672f6a6f73726f6d2f6c61726176656c2d616e616c79746963732f762f756e737461626c652e737667)](https://packagist.org/packages/josrom/laravel-analytics) [![License](https://camo.githubusercontent.com/1bb50b2ed406ee6bf4c6a82fa301dd705f590cb68be3d60745653ac01e525d04/68747470733a2f2f706f7365722e707567782e6f72672f6a6f73726f6d2f6c61726176656c2d616e616c79746963732f6c6963656e73652e737667)](https://packagist.org/packages/josrom/laravel-analytics) [![Total Downloads](https://camo.githubusercontent.com/e767db041ac972c5d147f2c1b90f5a66707ffce7f3482519845d2bc318eeedc5/68747470733a2f2f706f7365722e707567782e6f72672f6a6f73726f6d2f6c61726176656c2d616e616c79746963732f646f776e6c6f6164732e737667)](https://packagist.org/packages/josrom/laravel-analytics) [![Building](https://camo.githubusercontent.com/0aeb4d3d774dbf7c57197cf16402e344b29c77990e01a18d457b9c26d9cc923b/68747470733a2f2f6170692e7472617669732d63692e6f72672f6a6f73726f6d2f6c61726176656c2d616e616c79746963732e7376673f6272616e63683d6d6173746572)](https://travis-ci.org/josrom/laravel-analytics)

Quickstart
----------

[](#quickstart)

```
composer require josrom/laravel-analytics

```

You can use the facade `Analytics`.

To your `.env` add these variables and set them to your liking:

```
ANALYTICS_PROVIDER=GoogleAnalytics
ANALYTICS_TRACKING_ID=your-tracking-id

```

We support the whole configuration as environment variables. Please see Configuration section.

Finally, just above your `` closing tag place, this code:

```
{!! Analytics::render() !!}

```

**You now have Google Analytics working. Enjoy!**

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

[](#installation)

Add to your composer.json following lines

```
"require": {
	"josrom/laravel-analytics": "~12.0"
}

```

Add `Josrom\LaravelAnalytics\AnalyticsServiceProvider::class,` to `providers` in `app/config/app.php`.

Optional: Add `'Analytics' => Josrom\LaravelAnalytics\AnalyticsFacade::class,` to `aliases` in `app/config/app.php`.

Run `php artisan vendor:publish --provider="Josrom\LaravelAnalytics\AnalyticsServiceProvider"`

Then edit `analytics.php` in `config` to your needs. We do config merge in the service provider, so your local settings will stay the same.

For laravel 12.x please use the 12.x release.

```
"require": {
	"josrom/laravel-analytics": "~12.0"
}

```

For laravel 11.x please use the 11.x release.

```
"require": {
	"josrom/laravel-analytics": "~11.0"
}

```

For laravel 10.x please use the 10.x release.

```
"require": {
	"josrom/laravel-analytics": "~10.0"
}

```

For laravel 9.x please use the 9.x release.

```
"require": {
	"josrom/laravel-analytics": "~9.0"
}

```

For laravel 8.x please use the 4.x release.

```
"require": {
	"josrom/laravel-analytics": "~3.0"
}

```

For laravel 7.x please use the 3.x release.

```
"require": {
	"josrom/laravel-analytics": "~3.0"
}

```

For laravel 6.x please use the 2.x release.

```
"require": {
	"josrom/laravel-analytics": "~2.0"
}

```

For php &lt; 7.2 or laravel &lt; 6.0 please use the 1.x release.

```
"require": {
	"josrom/laravel-analytics": "~1.0"
}

```

Configuration
-------------

[](#configuration)

providerProvider to use, possible Providers are: `GoogleAnalytics`, `NoAnalytics`### Google Analytics

[](#google-analytics)

tracking\_idTracking ID, Your tracking id for Google Analyticstracking\_domainTracking domain, unset or set to "`auto`" for automatic fallbacktracker\_nameTracker namedisplay\_featuresenabling the display features plugin, possible values: `(true|false)`anonymize\_ipanonymize users ip, possible values: `(true|false)`auto\_trackauto tracking current pageview, possible values: `(true|false)`debugenabling the debug mode, possible values: `(true|false)`optimize\_idenabling the optimze feature of \[Google Analytics\]()### Environment-based Configuration

[](#environment-based-configuration)

You can configure the whole settings by changing/setting environment variables in your .env file. (Or .env.dusk file if you use Laravel Dusk).

Here is the mapping of configuration value and the environment-based names:

tracking\_idANALYTICS\_TRACKING\_IDtracking\_domainANALYTICS\_TRACKING\_DOMAIN (auto)tracker\_nameANALYTICS\_TRACKER\_NAME (t0)display\_featuresANALYTICS\_DISPLAY\_FEATURES (false)anonymize\_ipANALYTICS\_ANONYMIZE\_IP (true)auto\_trackANALYTICS\_AUTO\_TRACK (true)debugANALYTICS\_DEBUG (true on local environment)optimize\_idANALYTICS\_OPTIMIZE\_IDThis behaviour was integrated with version 1.3.2.

### Other

[](#other)

disable\_script\_blockYou can disable script block generation by configuration value, possible values: `(true|false)`, false by default.Usage
-----

[](#usage)

In controller action (or anywhere else) use following statement to track an event or page view:

```
//	tracking the current page view
Analytics::trackPage();	// only necessary if `auto_track` is false or Analytics::disableAutoTracking() was called before

//	tracking an event
Analytics::trackEvent('category', 'action');

//	tracking a custom line
Analytics::trackCustom("ga('send', ......"); // this line will be added within the tracking script

```

You can set an optional campaign for the tracking:

```
// creating a campaign
$campaign = new \Josrom\LaravelAnalytics\Data\Campaign('Sales2016');
$campaign->setMedium('web')->setSource('IT Magazine')->setKeyword('Hot stuff');
Analytics::setCampaign($campaign);

```

You can set an user id for the tracking:

```
// creating a campaign
Analytics::setUserId($userIdentificationHash);

```

In your view or layout template (e.g. a blade template) use the following statement:

```
{!! Analytics::render() !!}

```

For Google Analytics you should place the statement right below the `body` tag

```
{!! Analytics::render() !!}

```

### Dependency Injection

[](#dependency-injection)

You can inject the analytics provider by referencing the interface:

```
class PageController extends Controller
{
	public function show(\Josrom\LaravelAnalytics\Contracts\AnalyticsProviderInterface $analytics)
	{
		$analytics->setUserId(md5(\Auth::user()->id)); // identical to Analytics::setUserId(md5(\Auth::user()->id));
		return view('welcome');
	}
}

```

How to use
----------

[](#how-to-use)

The `GoogleAnalytics` Provider automatically controls the [local environment](https://developers.google.com/analytics/devguides/collection/analyticsjs/advanced#localhost) behaviour for testing purposes.

There is a builtin provider called `NoAnalytics`. This is for testing environments and tracks nothing. So you do not have to rewrite your code, simple select this `provider` in `analytics` configuration for your special environment configurations.

### Track a measurement without having javascript

[](#track-a-measurement-without-having-javascript)

1. Log in to Google Analytics and create custom definition. There you create a custom metrics. For example: Email opens, Integer type, min: 0 and max: 1 This will be available as `metric1`.
2. Within your mail template (or page template) you have to create a tracking image

    ``
3. That's it

Content Security Policy
-----------------------

[](#content-security-policy)

Since version 1.3 is a support for Content Security Policy integrated.

Please call the `withCSP()` on the provider interface instance.

Then use an additional package (or implement on your own) `martijnc/php-csp` and use the following code in your middleware or your javascript sending controller:

```
use Phpcsp\Security\ContentSecurityPolicyHeaderBuilder;

$policy = new ContentSecurityPolicyHeaderBuilder();

// Set the default-src directive to 'none'
$policy->addSourceExpression(ContentSecurityPolicyHeaderBuilder::DIRECTIVE_DEFAULT_SRC, 'none');

// Add the nonce to the script-src directive
$policy->addNonce(ContentSecurityPolicyHeaderBuilder::DIRECTIVE_SCRIPT_SRC, $analytics->withCSP()->cspNonce());

foreach ($policy->getHeaders(true) as $header) {
    header(sprintf('%s: %s', $header['name'], $header['value']));
}
```

The result looks like this:

```
array (size=1)
  0 =>
    array (size=2)
      'name' => string 'Content-Security-Policy' (length=23)
      'value' => string 'default-src 'none'; script-src 'nonce-RandomNonceStringFromAnalyticsProvider';' (length=58)
```

On rendering your analytics script the `nonce` attribute will be automatically added on your script tag.

API Documentation
-----------------

[](#api-documentation)

For the correct usage methods look at the `Josrom\LaravelAnalytics\Contracts\AnalyticsProviderInterface.php`

### Analytics::render()

[](#analyticsrender)

Context: Blade Templates, View

For rendering the correct javascript code. It is necessary to have it in all layout files to track your actions and page calls.

```
/**
 * returns the javascript code for embedding the analytics stuff
 *
 * @return string
 */
public function render();

```

### Analytics::trackPage()

[](#analyticstrackpage)

Context: Controller, Action code

For tracking a page view.

```
/**
 * track an page view
 *
 * @param null|string $page
 * @param null|string $title
 * @param null|string $hittype
 * @return void
 */
public function trackPage($page, $title, $hittype);

```

### Analytics::trackEvent()

[](#analyticstrackevent)

Context: Controller, Action code

For tracking an event

```
/**
 * track an event
 *
 * @param string $category
 * @param string $action
 * @param null|string $label
 * @param null|int $value
 * @return void
 */
public function trackEvent($category, $action, $label, $value);

```

### Analytics::trackCustom()

[](#analyticstrackcustom)

Context: Controller, Action code

For tracking a custom script line within the embedded analytics code.

```
/**
 * track any custom code
 *
 * @param string $customCode
 * @return void
 */
public function trackCustom($customCode);

```

### Analytics::enableDisplayFeatures()

[](#analyticsenabledisplayfeatures)

Context: Controller, Action code

Enabling display features, overriding the configuration setting `display_features`.

```
/**
 * enable display features
 *
 * @return GoogleAnalytics
 */
public function enableDisplayFeatures();

```

### Analytics::disableDisplayFeatures()

[](#analyticsdisabledisplayfeatures)

Context: Controller, Action code

Disabling display features, overriding the configuration setting `display_features`.

```
/**
 * disable display features
 *
 * @return GoogleAnalytics
 */
public function disableDisplayFeatures();

```

### Analytics::enableAutoTracking()

[](#analyticsenableautotracking)

Context: Controller, Action code

Enabling the auto tracking, overriding the configuration setting `auto_track`.

```
/**
 * enable auto tracking
 *
 * @return GoogleAnalytics
 */
public function enableAutoTracking();

```

### Analytics::disableAutoTracking()

[](#analyticsdisableautotracking)

Context: Controller, Action code

Disabling the auto tracking, overriding the configuration setting `auto_track`.

```
/**
 * disable auto tracking
 *
 * @return GoogleAnalytics
 */
public function disableAutoTracking();

```

### Analytics::trackMeasurementUrl()

[](#analyticstrackmeasurementurl)

Context: Blade Template, View

Sometimes you have to track measurements, e.g. opening an email newsletter. There you have no javascript at all.

```
/**
 * assembles an url for tracking measurement without javascript
 *
 * e.g. for tracking email open events within a newsletter
 *
 * @param string $metricName
 * @param mixed $metricValue
 * @param \Josrom\LaravelAnalytics\Data\Event $event
 * @param \Josrom\LaravelAnalytics\Data\Campaign $campaign
 * @param string|null $clientId
 * @param array $params
 * @return string
 */
public function trackMeasurementUrl($metricName, $metricValue, Event $event, Campaign $campaign, $clientId = null, array $params = array());

```

### Analytics::setUserId($userId)

[](#analyticssetuseriduserid)

Context: Controller, Action code

Adding an user id to analytics tracking. This user id is a user-dependent unique id. But be careful, you should have no direct relation to the special user itself - it should be unique per user for analyzing.

This user tracking is implemented at [Google Analytics](https://developers.google.com/analytics/devguides/collection/analyticsjs/cookies-user-id).

```
/**
 * sets an user id for user tracking
 *
 * @param string $userId
 * @return AnalyticsProviderInterface
 */
public function setUserId($userId);

```

### Analytics::unsetUserId()

[](#analyticsunsetuserid)

Context: Controller, Action code

Removing of an user id is also possible.

```
/**
 * unset an user id
 *
 * @return AnalyticsProviderInterface
 */
public function unsetUserId();

```

### Analytics::setCampaign($campaign)

[](#analyticssetcampaigncampaign)

Context: Controller, Action code

Adding a campaign to the current tracking.

This campaign tracking is documented for [Google Analytics](https://developers.google.com/analytics/devguides/collection/analyticsjs/field-reference#campaignName).

```
/**
 * sets a campaign
 *
 * @param Campaign $campaign
 * @return AnalyticsProviderInterface
 */
public function setCampaign(Campaign $campaign);

```

### Analytics::unsetCampaign()

[](#analyticsunsetcampaign)

Context: Controller, Action code

Removing of a campaign is also possible.

```
/**
 * unset a possible given campaign
 *
 * @return AnalyticsProviderInterface
 */
public function unsetCampaign();

```

### Analytics::enableScriptBlock()

[](#analyticsenablescriptblock)

Context: Controller, Action code

Enabling the rendering of the `...` block tags. Is enabled by default, so you do not have to call this.

```
/**
 * render script block
 *
 * @return GoogleAnalytics
 */
public function enableScriptBlock();

```

### Analytics::disableScriptBlock()

[](#analyticsdisablescriptblock)

Context: Controller, Action code

Disabling the rendering of the `...` block tags.

```
/**
 * do not render script block
 *
 * @return GoogleAnalytics
 */
public function disableScriptBlock();

```

### Analytics::enableEcommerceTracking()

[](#analyticsenableecommercetracking)

Context: Controller, Action code

Enabling ecommerce tracking.

```
/**
 * enable ecommerce tracking
 *
 * @return AnalyticsProviderInterface
 */
public function enableEcommerceTracking();

```

### Analytics::disableEcommerceTracking()

[](#analyticsdisableecommercetracking)

Context: Controller, Action code

Disabling ecommerce tracking.

```
/**
 * disable ecommerce tracking
 *
 * @return AnalyticsProviderInterface
 */
public function disableEcommerceTracking();

```

### Analytics::ecommerceAddTransaction()

[](#analyticsecommerceaddtransaction)

Context: Controller, Action code

Add ecommerce transaction to tracking code.

```
/**
 * ecommerce tracking - add transaction
 *
 * @param string $id
 * @param null|string $affiliation
 * @param null|float $revenue
 * @param null|float $shipping
 * @param null|float $tax
 * @param null|string $currency
 *
 * @return AnalyticsProviderInterface
 */
public function ecommerceAddTransaction($id, $affiliation = null, $revenue = null, $shipping = null, $tax = null, $currency = null);

```

The [multi currency](https://developers.google.com/analytics/devguides/collection/analyticsjs/ecommerce#multicurrency) tracking is supported with currency values defined [here](https://support.google.com/analytics/answer/6205902#supported-currencies).

### Analytics::ecommerceAddItem()

[](#analyticsecommerceadditem)

Context: Controller, Action code

Add ecommerce item to tracking code.

```
/**
 * ecommerce tracking - add item
 *
 * @param string $id
 * @param string $name
 * @param null|string $sku
 * @param null|string $category
 * @param null|float $price
 * @param null|int $quantity
 * @param null|string $currency
 *
 * @return AnalyticsProviderInterface
 */
public function ecommerceAddItem($id, $name, $sku = null, $category = null, $price = null, $quantity = null, $currency = null);

```

The [multi currency](https://developers.google.com/analytics/devguides/collection/analyticsjs/ecommerce#multicurrency) tracking is supported with currency values defined [here](https://support.google.com/analytics/answer/6205902#supported-currencies).

### Analytics::setCustom()

[](#analyticssetcustom)

Context: Controller, Action code

Adds custom settings.

```
/**
 * sets custom dimensions
 *
 * @param string|array $dimension
 * @param null|string $value
 * @return AnalyticsProviderInterface
 */
public function setCustom($dimension, $value = null)

```

### Analytics::withCSP()

[](#analyticswithcsp)

Context: Controller, Action code

Enabling the Content Security Policy feature.

```
/**
 * enables Content Security Polity and sets nonce
 *
 * @return AnalyticsProviderInterface
 */
public function withCSP();

```

### Analytics::withoutCSP()

[](#analyticswithoutcsp)

Context: Controller, Action code

Disabling the Content Security Policy feature.

```
/**
 * disables Content Security Polity
 *
 * @return AnalyticsProviderInterface
 */
public function withoutCSP();

```

### Analytics::cspNonce()

[](#analyticscspnonce)

Context: Controller, Action code

Returns the nonce generated for the Content Security Policy Header.

```
/**
 * returns the current Content Security Policy nonce
 *
 * @return string|null
 */
public function cspNonce();

```

### Analytics::setOptimizeId()

[](#analyticssetoptimizeid)

```
/**
 * set a custom optimize ID (the GTM-XXXXXX code)
 *
 * @param string $optimizeId
 *
 * @return AnalyticsProviderInterface
 */
public function setOptimizeId($optimizeId);

```

###  Health Score

50

—

FairBetter than 95% of packages

Maintenance77

Regular maintenance activity

Popularity10

Limited adoption so far

Community14

Small or concentrated contributor base

Maturity87

Battle-tested with a long release history

 Bus Factor3

3 contributors hold 50%+ of commits

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 ~133 days

Recently: every ~453 days

Total

33

Last Release

157d ago

Major Versions

3.0.0 → 4.0.02020-09-12

4.1.0 → 9.0.02025-02-07

9.0.0 → 10.0.02025-02-07

10.0.0 → 11.0.02025-02-07

11.0.0 → 12.0.02025-12-03

PHP version history (7 changes)1.0.3PHP &gt;=5.3.0

1.0.7PHP &gt;=5.4.0

2.0.0PHP ^7.2

4.1.0PHP ^7.2 || ^8.0

9.0.0PHP ^8.0

10.0.0PHP ^8.1

11.0.0PHP ^8.2

### Community

Maintainers

![](https://www.gravatar.com/avatar/57b1b8418c0389498a0ac7c0e2f5fe0757502e0d380e1099659d785fb71dd6be?d=identicon)[Josrom](/maintainers/Josrom)

---

Top Contributors

[![WaveHack](https://avatars.githubusercontent.com/u/1611537?v=4)](https://github.com/WaveHack "WaveHack (10 commits)")[![JoseVte](https://avatars.githubusercontent.com/u/3540836?v=4)](https://github.com/JoseVte "JoseVte (6 commits)")[![mvdnbrk](https://avatars.githubusercontent.com/u/802681?v=4)](https://github.com/mvdnbrk "mvdnbrk (5 commits)")[![justb81](https://avatars.githubusercontent.com/u/3680539?v=4)](https://github.com/justb81 "justb81 (4 commits)")[![mabasic](https://avatars.githubusercontent.com/u/1839930?v=4)](https://github.com/mabasic "mabasic (3 commits)")[![amirbilu](https://avatars.githubusercontent.com/u/7681048?v=4)](https://github.com/amirbilu "amirbilu (3 commits)")[![rokde](https://avatars.githubusercontent.com/u/4946056?v=4)](https://github.com/rokde "rokde (3 commits)")[![tuimz](https://avatars.githubusercontent.com/u/850235?v=4)](https://github.com/tuimz "tuimz (2 commits)")[![pdziewa](https://avatars.githubusercontent.com/u/2640714?v=4)](https://github.com/pdziewa "pdziewa (1 commits)")[![benrolfe](https://avatars.githubusercontent.com/u/474175?v=4)](https://github.com/benrolfe "benrolfe (1 commits)")[![agravelot](https://avatars.githubusercontent.com/u/13699253?v=4)](https://github.com/agravelot "agravelot (1 commits)")

---

Tags

phplaraveljavascriptanalyticsstatisticsgoogle-analytics

### Embed Badge

![Health badge](/badges/josrom-laravel-analytics/health.svg)

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

###  Alternatives

[prologue/alerts

Prologue Alerts is a package that handles global site messages.

3486.1M30](/packages/prologue-alerts)[bezhansalleh/filament-google-analytics

Google Analytics integration for FilamentPHP

205144.8k5](/packages/bezhansalleh-filament-google-analytics)[monicahq/laravel-cloudflare

Add Cloudflare ip addresses to trusted proxies for Laravel.

3372.7M4](/packages/monicahq-laravel-cloudflare)[laragear/preload

Effortlessly make a Preload script for your Laravel application.

119363.5k](/packages/laragear-preload)[panphp/pan

A simple, lightweight, and privacy-focused product analytics php package.

1.2k94.6k5](/packages/panphp-pan)[kra8/laravel-snowflake

Snowflake for Laravel and Lumen.

188402.3k6](/packages/kra8-laravel-snowflake)

PHPackages © 2026

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