Skip to content
Track pageviews server side using the Google Analytics Measurement Protocol.
Branch: master
Clone or download
Fetching latest commit…
Cannot retrieve the latest commit at this time.
Permalink
Type Name Latest commit message Commit time
Failed to load latest commit information.
config
resources/views
routes
src
.styleci.yml
CHANGELOG.md
README.md
composer.json

README.md

Track Pageviews Server Side using Google Analytics

Latest Version Software License StyleCI Total Downloads

Don't want nasty tricksy Google Analytics JS tracking code on your site but still want to have some idea of pageviews? This package uses Google's Measurement Protocol to record basic pageviews on your site. It uses a small chunk of Javascript to post page data via Ajax on window load which will get sent to Google using Guzzle.

Currently available for Laravel 5.7 & 5.8, looking into older versions.

Installation

You can install the package via composer:

composer require jamesfairhurst/laravel-google-analytics-pageviews

Optionally, you can publish the config file of the package.

php artisan vendor:publish --provider="JamesFairhurst\LaravelGoogleAnalyticsPageviews\PageviewsServiceProvider" --tag=config

The config file looks like:

<?php

return [
    // Are pageviews tracked?
    'enabled' => env('PAGEVIEWS_ENABLED', true),
    // Site's tracking id
    'google_analytics_tracking_id' => env('PAGEVIEWS_GOOGLE_ANALYTICS_TRACKING_ID', ''),
    // Route name used internally to send pageview to google
    'route' => 'pageviews.store',
];

Usage

Add the Google Analytics Property Tracking ID to your .env file

PAGEVIEWS_GOOGLE_ANALYTICS_TRACKING_ID=UA-xxxxxxx-xx

Next, add the @pageviews blade directive to any page you wish to track or in a layouts file to track all pages e.g.

    <script src="{{ mix('js/app.js') }}"></script>
    @pageviews
</body>

@pageviews will add a small chunk of Javascript that will send a POST XMLHttpRequest request on window.load to a package controller action that will record the pageview using Google's Measurement Protocol.

window.addEventListener("load",function(e){var t=new XMLHttpRequest;t.open("POST","{{ route('pageviews.store') }}",!0),t.setRequestHeader("Content-Type","application/x-www-form-urlencoded"),t.send("dp=/home&dt=Home&ua=Mozilla/5.0&dr=https://example.com")});

You can also explicitly disable tracking by adding PAGEVIEWS_ENABLED=false to your .env file which is useful to stop tracking locally.

Contributing

Pull requests are welcome. For major changes, please open an issue first to discuss what you would like to change.

License

MIT

You can’t perform that action at this time.