View code on Github
Access GA4 Data in Laravel
With the Laravel Analytics package, you can access GA4 data and properties in your Laravel application using simple, pre-built queries.
<?php
namespace App\Http\Controllers;
use Gtmassey\LaravelAnalytics\Analytics;
use Gtmassey\LaravelAnalytics\Period;
use Illuminate\View\View;
class AnalyticsController extends Controller
{
public function index(): View
{
$data = collect([
'userEngagement' => Analytics::getUserEngagement(),
'userAcquisitionOverview' => Analytics::getUserAcquisitionOverview(),
'topPages' => Analytics::getTopPages(),
'topEvents' => Analytics::getTopEvents(),
]);
return view('app.analytics', ['data' => $data]);
}
}
Build Custom Queries
The Laravel Analytics package also allows you to build and run custom GA4 Data Api queries.
<?php
namespace App\Http\Controllers;
use Gtmassey\LaravelAnalytics\Analytics;
use Gtmassey\LaravelAnalytics\Period;
use Illuminate\View\View;
class AnalyticsController extends Controller
{
public function index(): View
{
$report = Analytics::query()
->setMetrics(function (Metrics $metrics) {
return $metrics->active1DayUsers()
->active7DayUsers()
->active28DayUsers();
})->forPeriod(Period::defaultPeriod())
->run();
$report2 = Analytics::query()
->setMetrics(function (Metrics $metrics) {
return $metrics->sessions();
})->setDimensions(function (Dimensions $dimensions) {
return $dimensions->pageTitle();
})->forPeriod(Period::create(Carbon::now()->subDays(30), Carbon::now()))
->run();
return view('app.analytics', ['data' => collect([$report, $report2]);
}
}
The package allows users to define custom queries through callback methods on setMetrics()
and setDimensions()
. After passing in a period of time to run the report for, the GA4 query is built and processed by the package and a report response is generated in the form of an instance of the ResponseData
class.