Tracking events with Google Analytics and a new Laravel package
Yesterday I posted a tweet about a Google Analytics implementation I was working on. It was based on a Event/Listener solution using Laravel. The tweet quickly gained traction and one day later it was liked more than 170 times and I was encouraged to build a package out of it! Here we are, introducing the Laravel Analytics Event Tracking package.
Sending events to @googleanalytics with @laravelphp pic.twitter.com/Y7eljklSkX
— Pascal Baljet (@pascalbaljet) May 6, 2020
The idea is simple. Add the ShouldBroadcastToAnalytics
interface to an event and the package will perform an API call to Google Analytics to track the event. Under the hood we're using the theiconic/php-ga-measurement-protocol
package to make to actual call. There are some additional methods you can add to your event to customize the event, for example, to set the value of the event or to specify a category.
<?php namespace App\Events; use App\Order;use TheIconic\Tracking\GoogleAnalytics\Analytics;use Illuminate\Foundation\Events\Dispatchable;use Illuminate\Queue\SerializesModels;use ProtoneMedia\AnalyticsEventTracking\ShouldBroadcastToAnalytics; class OrderWasPaid implements ShouldBroadcastToAnalytics{ use Dispatchable, SerializesModels; public $order; public function __construct(Order $order) { $this->order = $order; } // optional public function withAnalytics(Analytics $analytics) { $analytics->setEventValue($this->order->sum_in_cents / 100); } // optional public function broadcastAnalyticsActionAs(Analytics $analytics) { return 'CustomEventAction'; }}
Google Analytics keeps track of visitors using a Client ID. This identifier is stored in a cookie and Google explicitly tells developers not to parse it themselves. Gladly their JavaScript implementation provides a way to extract the Client ID! This package comes with a Blade Directive that fetches the Client ID, sends it to your Laravel backend (using a POST request) and stores it in the session. Now we can track events with the visitor's Client ID.
The package is really easy to setup, check out the README to get started.