Analytics tracking package for Laravel
, (*1)
Quickstart
composer require ipunkt/laravel-analytics
You can use the facade Analytics
., (*2)
To your .env
add these variables and set them to your liking:, (*3)
ANALYTICS_PROVIDER=GoogleAnalytics
ANALYTICS_TRACKING_ID=your-tracking-id
We support the whole configuration as environment variables. Please see Configuration section., (*4)
Finally, just above your </head>
closing tag place, this code:, (*5)
{!! Analytics::render() !!}
You now have Google Analytics working. Enjoy!, (*6)
Installation
Add to your composer.json following lines, (*7)
"require": {
"ipunkt/laravel-analytics": "~3.0"
}
Add Ipunkt\LaravelAnalytics\AnalyticsServiceProvider::class,
to providers
in app/config/app.php
., (*8)
Optional: Add 'Analytics' => Ipunkt\LaravelAnalytics\AnalyticsFacade::class,
to aliases
in app/config/app.php
., (*9)
Run php artisan vendor:publish --provider="Ipunkt\LaravelAnalytics\AnalyticsServiceProvider"
, (*10)
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., (*11)
For laravel 7.x please use the 3.x release., (*12)
"require": {
"ipunkt/laravel-analytics": "~3.0"
}
For laravel 6.x please use the 2.x release., (*13)
"require": {
"ipunkt/laravel-analytics": "~2.0"
}
For php < 7.2 or laravel < 6.0 please use the 1.x release., (*14)
"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)., (*15)
Here is the mapping of configuration value and the environment-based names:, (*16)
- 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., (*17)
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:, (*18)
// 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:, (*19)
// 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:, (*20)
// creating a campaign
Analytics::setUserId($userIdentificationHash);
In your view or layout template (e.g. a blade template) use the following statement:, (*21)
{!! Analytics::render() !!}
For Google Analytics you should place the statement right below the body
tag, (*22)
<body>{!! Analytics::render() !!}
Dependency Injection
You can inject the analytics provider by referencing the interface:, (*23)
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., (*24)
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., (*25)
Track a measurement without having javascript
-
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
., (*26)
-
Within your mail template (or page template) you have to create a tracking image, (*27)
<img src="{!! Analytics::trackMeasurementUrl('metric1', '1', new Event, new Campaign, md5($user)) !!}" width="1" height="1" style="background-color: transparent; border: 0 none;" />
, (*28)
-
That's it, (*29)
Content Security Policy
Since version 1.3 is a support for Content Security Policy integrated., (*30)
Please call the withCSP()
on the provider interface instance., (*31)
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:, (*32)
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:, (*33)
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., (*34)
API Documentation
For the correct usage methods look at the Ipunkt\LaravelAnalytics\Contracts\AnalyticsProviderInterface.php
, (*35)
Analytics::render()
Context: Blade Templates, View, (*36)
For rendering the correct javascript code. It is necessary to have it in all layout files to track your actions and page calls., (*37)
/**
* returns the javascript code for embedding the analytics stuff
*
* @return string
*/
public function render();
Analytics::trackPage()
Context: Controller, Action code, (*38)
For tracking a page view., (*39)
/**
* 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, (*40)
For tracking an event, (*41)
/**
* 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, (*42)
For tracking a custom script line within the embedded analytics code., (*43)
/**
* track any custom code
*
* @param string $customCode
* @return void
*/
public function trackCustom($customCode);
Analytics::enableDisplayFeatures()
Context: Controller, Action code, (*44)
Enabling display features, overriding the configuration setting display_features
., (*45)
/**
* enable display features
*
* @return GoogleAnalytics
*/
public function enableDisplayFeatures();
Analytics::disableDisplayFeatures()
Context: Controller, Action code, (*46)
Disabling display features, overriding the configuration setting display_features
., (*47)
/**
* disable display features
*
* @return GoogleAnalytics
*/
public function disableDisplayFeatures();
Analytics::enableAutoTracking()
Context: Controller, Action code, (*48)
Enabling the auto tracking, overriding the configuration setting auto_track
., (*49)
/**
* enable auto tracking
*
* @return GoogleAnalytics
*/
public function enableAutoTracking();
Analytics::disableAutoTracking()
Context: Controller, Action code, (*50)
Disabling the auto tracking, overriding the configuration setting auto_track
., (*51)
/**
* disable auto tracking
*
* @return GoogleAnalytics
*/
public function disableAutoTracking();
Analytics::trackMeasurementUrl()
Context: Blade Template, View, (*52)
Sometimes you have to track measurements, e.g. opening an email newsletter. There you have no javascript at all., (*53)
/**
* 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, (*54)
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., (*55)
This user tracking is implemented at Google Analytics., (*56)
/**
* sets an user id for user tracking
*
* @param string $userId
* @return AnalyticsProviderInterface
*/
public function setUserId($userId);
Analytics::unsetUserId()
Context: Controller, Action code, (*57)
Removing of an user id is also possible., (*58)
/**
* unset an user id
*
* @return AnalyticsProviderInterface
*/
public function unsetUserId();
Analytics::setCampaign($campaign)
Context: Controller, Action code, (*59)
Adding a campaign to the current tracking., (*60)
This campaign tracking is documented for Google Analytics., (*61)
/**
* sets a campaign
*
* @param Campaign $campaign
* @return AnalyticsProviderInterface
*/
public function setCampaign(Campaign $campaign);
Analytics::unsetCampaign()
Context: Controller, Action code, (*62)
Removing of a campaign is also possible., (*63)
/**
* unset a possible given campaign
*
* @return AnalyticsProviderInterface
*/
public function unsetCampaign();
Analytics::enableScriptBlock()
Context: Controller, Action code, (*64)
Enabling the rendering of the <script>...</script>
block tags. Is enabled by default, so you do not have to call this., (*65)
/**
* render script block
*
* @return GoogleAnalytics
*/
public function enableScriptBlock();
Analytics::disableScriptBlock()
Context: Controller, Action code, (*66)
Disabling the rendering of the <script>...</script>
block tags., (*67)
/**
* do not render script block
*
* @return GoogleAnalytics
*/
public function disableScriptBlock();
Analytics::enableEcommerceTracking()
Context: Controller, Action code, (*68)
Enabling ecommerce tracking., (*69)
/**
* enable ecommerce tracking
*
* @return AnalyticsProviderInterface
*/
public function enableEcommerceTracking();
Analytics::disableEcommerceTracking()
Context: Controller, Action code, (*70)
Disabling ecommerce tracking., (*71)
/**
* disable ecommerce tracking
*
* @return AnalyticsProviderInterface
*/
public function disableEcommerceTracking();
Analytics::ecommerceAddTransaction()
Context: Controller, Action code, (*72)
Add ecommerce transaction to tracking code., (*73)
/**
* 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., (*74)
Analytics::ecommerceAddItem()
Context: Controller, Action code, (*75)
Add ecommerce item to tracking code., (*76)
/**
* 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., (*77)
Analytics::setCustom()
Context: Controller, Action code, (*78)
Adds custom settings., (*79)
/**
* 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, (*80)
Enabling the Content Security Policy feature., (*81)
/**
* enables Content Security Polity and sets nonce
*
* @return AnalyticsProviderInterface
*/
public function withCSP();
Analytics::withoutCSP()
Context: Controller, Action code, (*82)
Disabling the Content Security Policy feature., (*83)
/**
* disables Content Security Polity
*
* @return AnalyticsProviderInterface
*/
public function withoutCSP();
Analytics::cspNonce()
Context: Controller, Action code, (*84)
Returns the nonce generated for the Content Security Policy Header., (*85)
/**
* 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);