Google Analytics (GA4) Integration

Laravel Integration with Google Analytics (GA4): Improving Dashboard Performance with DB Cache and Scheduler

Meta Description:

A step-by-step guide to securely connecting Google Analytics (GA4) data to Laravel projects, caching the data in the database, and automatically updating it using a scheduler on a Linux server.

Keywords:

Laravel Google Analytics, GA4 Laravel integration, Laravel scheduler, Laravel analytics dashboard, GA4 API Laravel, Laravel analytics cache

Laravel Integration with Google Analytics (GA4)

In modern web dashboards, Google Analytics 4 (GA4) data is crucial for analyzing user behavior. However, in many projects, dashboard performance can decrease because GA data is pulled directly via API.

In this article:

  1. Connecting Laravel with Google Analytics GA4
  2. Caching API data in the database
  3. Improving dashboard performance
  4. Automatic data updates with Laravel Scheduler
  5. cron installation on a Linux server

We will explain the steps.

The structure used in this guide is explained using the FerhatGolge panel architecture , but the same method can be applied to all Laravel projects.

1. Establishing the Google Analytics (GA4) Connection

Creating a GA4 Service Account

To enable Laravel applications to access the GA4 API, a Service Account must be created.

Steps:

  1. Open Google Cloud Console
  2. Go to IAM & Admin → Service Accounts
  3. Create a new service account
  4. Generate and download JSON keys.
  5. On the GA4 panel
Admin → Access Management

Go to the section and add the service account as a Viewer .

2. Adding the JSON Key to the Laravel Project

For security reasons, the JSON key file should not be placed in the public folder .

Suggested folder:

storage/app/analytics/ferhatgolge-ga.json

Laravel can read this file directly.

3. GA4 Property ID Identification

The Property ID value found in the Google Analytics panel should be stored in the application's settings section.

Example:

PropertyId = 123456789

This value will be used in API queries.

4. JSON Path Setting

The system must read the path to the JSON file from the settings.

Example setting:

analytics/ferhatgolge-ga.json

Important safety note:

The JSON file should not be located in the public or uploads folder.

5. Testing the Connection

The following artisan command can be used to test that the GA4 connector is working correctly.


php artisan ga:fetch-dashboard-stats --days=30

This command verifies the system connection by retrieving GA data.

6. Storing GA Data with DB Cache

Storing data in the database instead of making an API call every time the dashboard page is opened significantly improves performance.

Advantages:

  1. API limits are reduced.
  2. Dashboard opens faster.
  3. API errors do not affect the user.

Creating Migration


php artisan make:migration create_ga_dashboard_stats_table

Example table structure:

column description
date_range_daysdata range (7, 30 etc.)
summarygeneral statistics
countriescountry data
devicesdevice data
pagespage performance
fetched_atdata retrieval time

Model Creation


php artisan make:model GaDashboardStats

It is necessary to cast the JSON fields within the model.


protected $casts = [
'summary' => 'array',
'countries' => 'array',
'devices' => 'array',
'pages' => 'array',
'fetched_at' => 'datetime',
];

7. Artisan Command that Retrieves GA Data

In Laravel, we can create an Artisan Command to retrieve GA data and write it to the database.

Creating commands:


php artisan make:command FetchGaDashboardStats

Example data payload:


$payload = [
'summary' => $analyticsService->getAnalyticsSummary($days),
'countries' => $analyticsService->getTopCountries($days, 5),
'devices' => $analyticsService->getTopDevices($days),
'pages' => $analyticsService->getTopPages($days, 5),
'fetched_at' => now(),
];

GaDashboardStats::updateOrCreate(
['date_range_days' => $days],
$payload
);

8. Installing Laravel Scheduler

Laravel Scheduler can be used to regularly update GA data.


Schedule::command(FetchGaDashboardStats::class)->hourly();

This command will run automatically every hour.

9. Reading Data from the Dashboard

Dashboard will now read data from the DB cache instead of directly from the API.


$gaStats = GaDashboardStats::where('date_range_days', 30)->first();

$analytics['data'] = $gaStats->summary ?? [];
$analytics['countries'] = $gaStats->countries ?? [];
$analytics['devices'] = $gaStats->devices ?? [];
$analytics['pages'] = $gaStats->pages ?? [];
$analytics['fetched_at'] = optional($gaStats->fetched_at)->format('dmY H:i');

This method significantly improves dashboard performance.

10. Autorunning on Ubuntu/Linux Server

Deploy Commands


composer install --no-dev
php artisan migrate --force
php artisan config:cache
php artisan route:cache
php artisan view:cache

Defining Cron Jobs

For Laravel scheduler to work, a cron job must be added.


* * * * * cd /var/www/ferhatgolge && php artisan schedule:run >> /dev/null 2>&1

To add it to the server:


crontab -e

File Permissions


chown -R www-data:www-data storage bootstrap/cache
chmod -R 775 storage bootstrap/cache

Troubleshooting

GA data is coming back empty.

  1. Is the Property ID correct?
  2. Is the service account authorized within GA4?

The JSON file cannot be read.

  1. Is the file inside the storage?
  2. Are the file permissions correct?

API access error

Is the Analytics Data API active in Google Cloud?

Time difference problem

Make sure the server clock is correct.

Conclusion

Using DB caching for Google Analytics data in Laravel, instead of pulling data directly from the API , significantly improves dashboard performance.

Thanks to this architecture:

  1. GA API calls decrease.
  2. Dashboard loads faster.
  3. Data is updated regularly.
  4. The system operates more stably.


Comments

Log in or sign up to write a comment
Giriş
Sign Up