• This repository has been archived on 18/Feb/2022
  • Stars
    star
    264
  • Rank 154,627 (Top 4 %)
  • Language
    PHP
  • License
    MIT License
  • Created over 10 years ago
  • Updated over 3 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Analytics tracking package for Laravel

Analytics tracking package for Laravel

Latest Stable Version Latest Unstable Version License Total Downloads Building

Quickstart

composer require ipunkt/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 </head> closing tag place, this code:

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

You now have Google Analytics working. Enjoy!

Installation

Add to your composer.json following lines

"require": {
	"ipunkt/laravel-analytics": "~3.0"
}

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

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

Run php artisan vendor:publish --provider="Ipunkt\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 7.x please use the 3.x release.

"require": {
	"ipunkt/laravel-analytics": "~3.0"
}

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

"require": {
	"ipunkt/laravel-analytics": "~2.0"
}

For php < 7.2 or laravel < 6.0 please use the 1.x release.

"require": {
	"ipunkt/laravel-analytics": "~1.0"
}

Configuration

provider
Provider to use, possible Providers are: GoogleAnalytics, NoAnalytics

Google Analytics

tracking_id
Tracking ID, Your tracking id for Google Analytics
tracking_domain
Tracking domain, unset or set to "auto" for automatic fallback
tracker_name
Tracker name
display_features
enabling the display features plugin, possible values: (true|false)
anonymize_ip
anonymize users ip, possible values: (true|false)
auto_track
auto tracking current pageview, possible values: (true|false)
debug
enabling the debug mode, possible values: (true|false)
optimize_id
enabling the optimze feature of [Google Analytics](https://support.google.com/optimize/answer/6262084)

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_id
ANALYTICS_TRACKING_ID
tracking_domain
ANALYTICS_TRACKING_DOMAIN (auto)
tracker_name
ANALYTICS_TRACKER_NAME (t0)
display_features
ANALYTICS_DISPLAY_FEATURES (false)
anonymize_ip
ANALYTICS_ANONYMIZE_IP (true)
auto_track
ANALYTICS_AUTO_TRACK (true)
debug
ANALYTICS_DEBUG (true on local environment)
optimize_id
ANALYTICS_OPTIMIZE_ID

This behaviour was integrated with version 1.3.2.

Other

disable_script_block
You can disable script block generation by configuration value, possible values: (true|false), false by default.

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 \Ipunkt\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

<body>{!! Analytics::render() !!}

Dependency Injection

You can inject the analytics provider by referencing the interface:

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

How to use

The GoogleAnalytics Provider automatically controls the local environment 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

  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

    <img src="{!! Analytics::trackMeasurementUrl('metric1', '1', new Event, new Campaign, md5($user)) !!}" width="1" height="1" style="background-color: transparent; border: 0 none;" />

  3. That's it

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

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

Analytics::render()

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()

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()

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()

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()

Context: Controller, Action code

Enabling display features, overriding the configuration setting display_features.

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

Analytics::disableDisplayFeatures()

Context: Controller, Action code

Disabling display features, overriding the configuration setting display_features.

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

Analytics::enableAutoTracking()

Context: Controller, Action code

Enabling the auto tracking, overriding the configuration setting auto_track.

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

Analytics::disableAutoTracking()

Context: Controller, Action code

Disabling the auto tracking, overriding the configuration setting auto_track.

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

Analytics::trackMeasurementUrl()

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 \Ipunkt\LaravelAnalytics\Data\Event $event
 * @param \Ipunkt\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)

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.

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

Analytics::unsetUserId()

Context: Controller, Action code

Removing of an user id is also possible.

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

Analytics::setCampaign($campaign)

Context: Controller, Action code

Adding a campaign to the current tracking.

This campaign tracking is documented for Google Analytics.

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

Analytics::unsetCampaign()

Context: Controller, Action code

Removing of a campaign is also possible.

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

Analytics::enableScriptBlock()

Context: Controller, Action code

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

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

Analytics::disableScriptBlock()

Context: Controller, Action code

Disabling the rendering of the <script>...</script> block tags.

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

Analytics::enableEcommerceTracking()

Context: Controller, Action code

Enabling ecommerce tracking.

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

Analytics::disableEcommerceTracking()

Context: Controller, Action code

Disabling ecommerce tracking.

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

Analytics::ecommerceAddTransaction()

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 tracking is supported with currency values defined here.

Analytics::ecommerceAddItem()

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 tracking is supported with currency values defined here.

Analytics::setCustom()

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()

Context: Controller, Action code

Enabling the Content Security Policy feature.

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

Analytics::withoutCSP()

Context: Controller, Action code

Disabling the Content Security Policy feature.

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

Analytics::cspNonce()

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()

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

More Repositories

1

docker-laravel-queue-worker

A docker image for working with queues being monitored by supervisor as recommended by laravel.
Dockerfile
70
star
2

docker-libreoffice-headless

Libreoffice as headless docker container
Dockerfile
36
star
3

laravel-oauth-introspection

OAuth 2.0 Token Introspection (RFC 7662)
PHP
19
star
4

KanboardSearch

PHP
17
star
5

subscriptions

Subscription handling package for laravel applications
PHP
13
star
6

docker-gulp-tasks

Docker-Image with ready-to-use Gulp-Tasks
JavaScript
10
star
7

laravel-healthcheck

configurable healthcheck route for laravel
PHP
10
star
8

docker-xtrabackup

xtrabackup with entrypoint script
Shell
9
star
9

laravel-repositories

Base repository implementation for laravel 4.x
PHP
7
star
10

KanboardTaskButtonsReposition

This Plugin makes it possible to reassemble task template to move some action buttons from sidebar list to corresponding accordion section in sidebar content.
PHP
7
star
11

laravel-socialite-profiles

A Laravel Socialite extension for having multiple social network profiles being attached.
PHP
7
star
12

rancherize

Rancherize your development workflow
PHP
6
star
13

laravel-route-cache

Simple Cache for Laravel Routes sending 304 and cached static content
PHP
5
star
14

laravel-notify

Provides an ready to use object oriented notification interface for laravel 4, including working example javascript and css for Twitter Bootstrap 3
PHP
5
star
15

KanboardProjectInvitation

Plugin is used to invite new users to actual Project by typing user's email.
PHP
5
star
16

KanboardOffline

CSS
5
star
17

laravel-rabbitmq

[DEPRECATED] Interact with RabbitMQ with raw message data to interact with microservices of any language.
PHP
5
star
18

laravel-json-api

JSON Api Package for Laravel, standard compliant with jsonapi.org
PHP
4
star
19

KanboardCommentActions

PHP
4
star
20

permissions

Check your permissions with a simple 1-liner: $user->can('do something', $onAnObject)
PHP
4
star
21

fileproxy

A Laravel-based file proxy application. Ready to go.
PHP
3
star
22

laravel-jaeger

Write basic laravel request informations to jaeger tracing
PHP
3
star
23

composer-about

Parses composer.lock and returns informations about the used packages
PHP
3
star
24

rancher-hetzner-lb

Create Hetzner Cloud hosts which manage a floating ip between them using pacemaker
Shell
2
star
25

laravel-notifications

Notifications package for laravel 4.x
PHP
2
star
26

ractivejs-loader

JavaScript
1
star
27

laravel-json-api-doc

parse an ipunkt/laravel-json-api based api definition and write a blueprint api documentation for it
HTML
1
star
28

laravel-two-factor-authentication

Two Factor Authentication for laravel apps
PHP
1
star
29

docker-prestashop

prestashop image with bcmath extension to use with rabbitmq
1
star
30

rancherize-jaeger

jaeger-agent sidekick for rancherize
PHP
1
star
31

catalog

catalog with rancher 1.6 infrastructure stacks - firewall,allow nfs,setup loadbalancer
1
star
32

docker-isso

isso with environment based configuration
Shell
1
star
33

laravel-jaeger-guzzle

Pass traces from ipunkt/laravel-jaeger to guzzle requests
PHP
1
star
34

laravel-indexer-service

A laravel microservice for selecting/creating/updating/deleting resource items within a connected solr core.
PHP
1
star
35

docker-revive-adserver

WORK IN PROGRESS! This project aims to have a usable, updatable installation of the revive adserver in a docker infrastructure.
Shell
1
star
36

calendar

PHP Library for reading and writing ical/ics calendar files
PHP
1
star
37

docker-hetzner-failover-ip

Docker image providing the hetzner failover ip python script and python with the required modules
Python
1
star
38

laravel-package-manager

Provides more comfort in using and developing php laravel packages
PHP
1
star
39

laravel-jaeger-rabbitmq

Integrate ipunkt/laravel-enqueue-rabbitmq with ipunkt/laravel-jaeger
PHP
1
star
40

social-auth

social-auth uses laravel 4.* to wrap around an oauth library to provide 3rd party auth simply by adding their credentials to your config
PHP
1
star
41

rancherize-blueprint-php-cli

PHP
1
star
42

rancher-hetzner-mariadb

Create Hetzner Cloud hosts which manage drbd, mariadb and a floating ip between them using pacemaker
Shell
1
star
43

rancher-varnish

Varnish using monit and confd based on rawmind0/alpine-traefik
Dockerfile
1
star
44

data-transformer

Data-transformer can easily transform data from source into target. All GDPR related data will be faked.
PHP
1
star
45

docker-fineuploader

[WIP] Docker container for fineuploader, upload to volume or s3
JavaScript
1
star
46

rancherize-drain

Publish via traefiks rancher provider but with an intermediate rancher loadbalancer sl drain_timeout_ms takes effect
PHP
1
star