devpro/laravel-ga4-event-tracking

This package is abandoned and no longer maintained. The author suggests using the luketowers/laravel-ga4-event-tracking package instead.

Simplifies using the Measurement Protocol for Google Analytics 4 to track events in Laravel applications.

v2.0.0 2024-09-19 20:48 UTC

This package is auto-updated.

Last update: 2024-09-19 20:51:56 UTC


README

Version Tests License

Simplifies using the Measurement Protocol for Google Analytics 4 to track events in Laravel applications.

Installation

  1. Install package via Composer
composer require luketowers/laravel-ga4-event-tracking
  1. Set GA4_MEASUREMENT_ID and GA4_MEASUREMENT_PROTOCOL_API_SECRET in your .env file.

Copy from Google Analytics > Admin > Data Streams > [Select Site] > Measurement ID & Google Analytics > Admin > Data Streams > [Select Site] > Measurement Protocol API secrets respectively.

  1. Optional: Publish the config / view files by running this command in your terminal:
php artisan vendor:publish --tag=ga4-event-tracking.config --tag=ga4-event-tracking.views
  1. Include the sendGA4ClientID directive in your layout file after the Google Analytics Code tracking code.
<!-- Google Analytics Code -->
@sendGA4ClientID
<!-- </head> -->

The client_id is required to send an event to Google Analytics. This package provides a Blade directive which you can put in your layout file after the Google Analytics Code tracking code. It grabs the current user's GA client_id from either the ga() or gtag() helper functions injected by Google Analytics and makes a POST request to your application to store the client_id in the session, which is later used by the DispatchAnalyticsJob when sending events to GA4.

If you do not use this blade directive, you will have to handle retrieving, storing, and sending the client_id yourself. You can use GA$::setClientId($clientId) to set the client_id manually.

Usage

This package provides two ways to send events to Google Analytics 4:

Directly via the GA4 facade:

Sending event directly is as simple as calling the sendEvent($eventData) method on the GA4 facade from anywhere in your backend to post event to Google Analytics 4. $eventData contains the name and params of the event as per this reference page. For example:

GA4::sendEvent([
    'name' => 'login',
    'params' => [
        'method' => 'Google',
    ],
]);

The sendEvent() method will return an array with the status of the request.

Broadcast events to GA4 via the Laravel Event System

Just add the ShouldBroadcastToAnalytics interface to your event, and you're ready! You don't have to manually bind any listeners.

<?php

namespace App\Events;

use App\Order;
use LukeTowers\GA4EventTracking\ShouldBroadcastToAnalytics;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;

class OrderWasCreated implements ShouldBroadcastToAnalytics
{
    use Dispatchable, SerializesModels;

    public $order;

    public function __construct(Order $order)
    {
        $this->order = $order;
    }
}

There are additional methods that let you customize the call sent to GA4.

broadcastGA4EventAs

With this method you can customize the name of the Event Action. By default, we use the class name with the class's namespace removed. This method gives you access to the underlying GA4 class instance as well.

eventOccurredAt

With this method you can customize the time that the event occurred at. This will be used in the timestamp_micros parameter sent to the Measurement Protocol. By default, we use the current time. You must return an instance of Carbon\Carbon in order for it to be used.

use Carbon\Carbon;
use LukeTowers\GA4EventTracking\GA4;
use LukeTowers\GA4EventTracking\ShouldBroadcastToAnalytics;
use Illuminate\Queue\SerializesModels;

class OrderSubmitted extends Event implements ShouldBroadcastToAnalytics
{
    use SerializesModels;

    protected Carbon $submittedAt;

    public function __construct(
        public Order $order
    ) {
        $this->submittedAt = now();
    }

    public function eventOccurredAt(): Carbon
    {
        return $this->submittedAt;
    }
}

withGA4Parameters

With this method you can set the parameters of the event being sent.

<?php

namespace App\Events;

use App\Order;
use LukeTowers\GA4EventTracking\ShouldBroadcastToAnalytics;
use LukeTowers\GA4EventTracking\GA4;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;

class OrderWasCreated implements ShouldBroadcastToAnalytics
{
    use Dispatchable, SerializesModels;

    public $order;

    public function __construct(Order $order)
    {
        $this->order = $order;
    }

    public function withGA4Parameters(GA4 $ga4): array
    {
        $eventData = [
            'transaction_id' => $order->id,
            'value' => $order->amount_total,
            'currency' => 'USD',
            'tax' => $order->amount_tax,
            'shipping' => $order->amount_shipping,
            'items' => [],
            'event_category' => config('app.name'),
            'event_label' => 'Order Created',
        ];

        foreach ($order->items as $item) {
            $eventData['items'][] = [
                'id' => $item->sku ?: 'p-' . $item->product->id,
                'name' => $item->title,
                'brand' => $item->product->brand->name ?? '',
                'category' => $item->product->category->title ?? '',
                'quantity' => $item->quantity,
                'price' => $item->price,
                'variant' => $item->variant->title ?? '',
            ];
        }

        return $eventData;
    }

    public function broadcastGA4EventAs(GA4 $ga4): string
    {
        return 'purchase';
    }
}

Handle framework and 3rd-party events

If you want to handle events where you can't add the ShouldBroadcastToAnalytics interface, you can manually register them in your EventServiceProvider using the DispatchAnalyticsJob listener.

<?php

namespace App\Providers;

use LukeTowers\GA4EventTracking\Listeners\DispatchAnalyticsJob;
use Illuminate\Auth\Events\Registered;
use Illuminate\Auth\Listeners\SendEmailVerificationNotification;
use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider;

class EventServiceProvider extends ServiceProvider
{
    /**
     * The event listener mappings for the application.
     *
     * @var array
     */
    protected $listen = [
        Registered::class => [
            SendEmailVerificationNotification::class,
            DispatchAnalyticsJob::class,
        ],
    ];
}

Debugging Mode

You can also enable debugging mode by calling enableDebugging() method before calling the sendEvent() method. Like so - GA4::enableDebugging()->sendEvent($eventData). The sendEvent() method will return the response (array) from Google Analytics request in that case.

Testing

composer test

or

./vendor/bin/phpunit

Security

If you discover any security related issues, please use the Report a vulnerability button instead of using the issue tracker.

Credits:

This package is a fork of the following projects:

License

This package is open-sourced software licensed under the MIT License.