├── routes
└── web.php
├── src
├── Facades
│ └── GA4.php
├── Http
│ └── Controllers
│ │ └── StoreGoogleAnalyticsClientIdController.php
├── GA4ServiceProvider.php
└── GA4MeasurementProtocol.php
├── config
└── google-analytics-4-measurement-protocol.php
├── CHANGELOG.md
├── resources
└── views
│ └── components
│ └── google-analytics-client-id.blade.php
├── LICENCE
├── composer.json
└── README.md
/routes/web.php:
--------------------------------------------------------------------------------
1 | middleware('web');
7 |
--------------------------------------------------------------------------------
/src/Facades/GA4.php:
--------------------------------------------------------------------------------
1 | env('MEASUREMENT_ID', null), # Same as Google Analytics Tracking ID
5 |
6 | 'api_secret' => env('MEASUREMENT_PROTOCOL_API_SECRET', null),
7 |
8 | 'client_id_session_key' => 'google-analytics-4-measurement-protocol.client_id'
9 | ];
10 |
--------------------------------------------------------------------------------
/CHANGELOG.md:
--------------------------------------------------------------------------------
1 | # Changelog
2 |
3 | All notable changes to `:package_name` will be documented in this file.
4 |
5 | ## 2.0.0 - 2025-02-26
6 | - Support for Laravel 12
7 |
8 | ## 1.3.0 - 2025-01-06
9 | - Support for Laravel 11
10 |
11 | ## 1.2.0 - 2023-09-08
12 | - Support for Laravel 10
13 |
14 | ## 1.1.0 - 2022-05-28
15 | - Support for Laravel 9
16 |
17 | ## 1.0.0 - 2021-03-19
18 | - initial release
19 |
--------------------------------------------------------------------------------
/src/Http/Controllers/StoreGoogleAnalyticsClientIdController.php:
--------------------------------------------------------------------------------
1 | request('client_id')]);
10 | }
11 | }
12 |
--------------------------------------------------------------------------------
/resources/views/components/google-analytics-client-id.blade.php:
--------------------------------------------------------------------------------
1 |
29 |
--------------------------------------------------------------------------------
/LICENCE:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) Freshbits Web Solutions info@freshbits.in
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
--------------------------------------------------------------------------------
/src/GA4ServiceProvider.php:
--------------------------------------------------------------------------------
1 | name('laravel-google-analytics-4-measurement-protocol')
19 | ->hasConfigFile()
20 | ->hasViews()
21 | ->hasRoute('web');
22 | }
23 |
24 | public function registeringPackage()
25 | {
26 | $this->app->bind('ga4', function () {
27 | return new GA4MeasurementProtocol();
28 | });
29 | }
30 |
31 | public function bootingPackage()
32 | {
33 | Blade::component('google-analytics-4-measurement-protocol::components.google-analytics-client-id', 'google-analytics-client-id');
34 | }
35 | }
36 |
--------------------------------------------------------------------------------
/composer.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "freshbitsweb/laravel-google-analytics-4-measurement-protocol",
3 | "description": "A Laravel package to use Measurement Protocol for Google Analytics 4",
4 | "require": {
5 | "php": "^7.4|^8.0",
6 | "guzzlehttp/guzzle": "^6.0|^7.0",
7 | "illuminate/http": "^7.0|^8.0|^9.0|^10.0|^11.0|^12.0",
8 | "illuminate/view": "^7.0|^8.0|^9.0|^10.0|^11.0|^12.0",
9 | "spatie/laravel-package-tools": "^1.5"
10 | },
11 | "require-dev": {
12 | "phpunit/phpunit": "^9|^10.5|^11.0"
13 | },
14 | "license": "MIT",
15 | "keywords": [
16 | "freshbitsweb",
17 | "laravel-google-analytics-4-measurement-protocol"
18 | ],
19 | "homepage": "https://github.com/freshbitsweb/laravel-google-analytics-4-measurement-protocol",
20 | "authors": [
21 | {
22 | "name": "Gaurav Makhecha",
23 | "email": "info@freshbits.in",
24 | "role": "Developer"
25 | }
26 | ],
27 | "autoload": {
28 | "psr-4": {
29 | "Freshbitsweb\\LaravelGoogleAnalytics4MeasurementProtocol\\": "src/"
30 | }
31 | },
32 | "autoload-dev": {
33 | "psr-4": {
34 | "Freshbitsweb\\LaravelGoogleAnalytics4MeasurementProtocol\\Tests\\": "tests"
35 | }
36 | },
37 | "scripts": {
38 | "test": "vendor/bin/phpunit --colors=always"
39 | },
40 | "config": {
41 | "sort-packages": true
42 | },
43 | "minimum-stability": "dev",
44 | "prefer-stable": true,
45 | "extra": {
46 | "laravel": {
47 | "providers": [
48 | "Freshbitsweb\\LaravelGoogleAnalytics4MeasurementProtocol\\GA4ServiceProvider"
49 | ],
50 | "aliases": {
51 | "GA4": "Freshbitsweb\\LaravelGoogleAnalytics4MeasurementProtocol\\Facades\\GA4"
52 | }
53 | }
54 | }
55 | }
56 |
--------------------------------------------------------------------------------
/src/GA4MeasurementProtocol.php:
--------------------------------------------------------------------------------
1 | clientId = $clientId;
26 |
27 | return $this;
28 | }
29 |
30 | public function enableDebugging(): self
31 | {
32 | $this->debugging = true;
33 |
34 | return $this;
35 | }
36 |
37 | public function postEvent(array $eventData): array
38 | {
39 | if (!$this->clientId && !$this->clientId = session(config('google-analytics-4-measurement-protocol.client_id_session_key'))) {
40 | throw new Exception('Please use the package provided blade directive or set client_id manually before posting an event.');
41 | }
42 |
43 | $response = Http::withOptions([
44 | 'query' => [
45 | 'measurement_id' => config('google-analytics-4-measurement-protocol.measurement_id'),
46 | 'api_secret' => config('google-analytics-4-measurement-protocol.api_secret'),
47 | ],
48 | ])->post($this->getRequestUrl(), [
49 | 'client_id' => $this->clientId,
50 | 'events' => [$eventData],
51 | ]);
52 |
53 | if ($this->debugging) {
54 | return $response->json();
55 | }
56 |
57 | return [
58 | 'status' => $response->successful()
59 | ];
60 | }
61 |
62 | private function getRequestUrl(): string
63 | {
64 | $url = 'https://www.google-analytics.com';
65 | $url .= $this->debugging ? '/debug' : '';
66 |
67 | return $url.'/mp/collect';
68 | }
69 | }
70 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | [](https://plant.treeware.earth/freshbitsweb/laravel-google-analytics-4-measurement-protocol)
2 |
3 | # Laravel Google Analytics 4 Measurement Protocol
4 | A Laravel package to use [Measurement Protocol for Google Analytics 4](https://developers.google.com/analytics/devguides/collection/protocol/ga4).
5 |
6 | ## Introduction
7 | This package allows you to post events to Google Analytics 4 from your Laravel backend.
8 |
9 | ## Supported Laravel versions
10 | - Laravel 7.x
11 | - Laravel 8.x
12 | - Laravel 9.x
13 | - Laravel 10.x
14 | - Laravel 11.x
15 | - Laravel 12.x
16 |
17 | ## Installation
18 | 1) Install the package by running this command in your terminal/cmd:
19 | ```bash
20 | composer require freshbitsweb/laravel-google-analytics-4-measurement-protocol
21 | ```
22 |
23 | 2) Set `MEASUREMENT_ID` and `MEASUREMENT_PROTOCOL_API_SECRET` in your .env file.
24 | You can get them from: Google Analytics > Admin > Data Streams > [Select Site] > Measurement Protocol API secrets
25 |
26 | 3) Optional: You can publish the config file by running this command in your terminal/cmd:
27 | ```bash
28 | php artisan vendor:publish --tag=google-analytics-4-measurement-protocol-config
29 | ```
30 |
31 | 4) `client_id` is required to post an event to Google Analytics. This package provides a Blade component which you can put in your layout file after the Google Analytics Code tracking code. It makes a POST request to the backend to store the client id in the session which is later used to post events to Google Analytics 4.
32 |
33 | ```html
34 |
35 |
36 |
37 | ```
38 |
39 | The other option is to call the `setClientId($clientId)` method on the `GA4` facade everytime before calling the `postEvent()` method.
40 |
41 | ## Usage
42 |
43 | You can simple call `GA4::postEvent($eventData)` 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](https://developers.google.com/analytics/devguides/collection/protocol/ga4/reference/events#login). For example:
44 |
45 | ```php
46 | GA4::postEvent([
47 | 'name' => 'login',
48 | 'params' => [
49 | 'method' => 'Google',
50 | ],
51 | ]);
52 | ```
53 |
54 | `postEvent()` method will return an array with the status of the request.
55 |
56 | ### Debugging Mode
57 |
58 | You can also enable [debugging mode](https://developers.google.com/analytics/devguides/collection/protocol/ga4/validating-events) by calling `enableDebugging()` method before calling the `postEvent()` method. Like so - `GA4::enableDebugging()->postEvent($eventData)`. The `postEvent()` method will return the response (array) from Google Analytics request in that case.
59 |
60 | ## Authors
61 |
62 | * [**Gaurav Makhecha**](https://github.com/gauravmak) - *Initial work*
63 |
64 | See also the list of [contributors](https://github.com/freshbitsweb/laravel-google-analytics-4-measurement-protocol/graphs/contributors) who participated in this project.
65 |
66 | ## License
67 |
68 | This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details
69 |
70 | ## Treeware
71 |
72 | You're free to use this package, but if it makes it to your production environment I would highly appreciate you buying the world a tree.
73 |
74 | It’s now common knowledge that one of the best tools to tackle the climate crisis and keep our temperatures from rising above 1.5C is to plant trees. If you contribute to our forest you’ll be creating employment for local families and restoring wildlife habitats.
75 |
76 | You can buy trees at for our forest here [offset.earth/treeware](https://plant.treeware.earth/freshbitsweb/laravel-google-analytics-4-measurement-protocol)
77 |
78 | Read more about Treeware at [treeware.earth](http://treeware.earth)
79 |
80 | ## Special Thanks to
81 |
82 | * [Laravel](https://laravel.com) Community
83 |
--------------------------------------------------------------------------------