spatie/laravel-analytics

repository·main·Indexed 25 days ago

https://github.com/spatie/laravel-analytics

A Laravel package providing a simple interface to retrieve data from the Google Analytics Data API (GA4). It includes helper methods to fetch most visited pages, visitors, page views, top referrers, user types, browsers, countries, and operating systems. The package also supports custom historical and realtime queries via get() and getRealtime() methods, allows for dimension and metric filtering using FilterExpression, and provides a mechanism to fake analytics calls during testing.

Tokens
5.4K
Snippets
18
Records
39
Agent score
85%

What's inside spatie/laravel-analytics

  1. Upgrade to v5 (Google Analytics 4)

    main
    Starting from version 5, laravel-analytics leverages the Google Analytics 4 (GA4) Data API instead of the Universal Analytics API. This transition involves breaking changes in method return structures and requires enabling the new API in the Google Cloud Console.
  2. Obtain Google Analytics credentials

    main

    To communicate with the Google Analytics Data API, follow these steps:

    1. Create a Project: Go to the Google API Console and create a project.
    2. Enable API: Search for and enable the "Google Analytics Data API".
    3. Create Service Account: Go to the "Credentials" section and create a "Service account key".
    4. Download JSON: Create a new key for the service account, select "JSON" as the type, and download the file.
    5. Store Credentials: Save this JSON file in your Laravel project (e.g., in storage/app/analytics/) and update service_account_credentials_json in your config. Do not commit this file to version control.
  3. Fake Analytics calls in tests

    main

    Use the Analytics::fake() method on the Spatie\Analytics\Facades\Analytics facade to prevent real API calls during testing.

    You can call fake() without arguments to simply intercept calls, or pass an array/collection to specify the exact data that should be returned when methods are called.

    <?php
    
    use Spatie\Analytics\Facades\Analytics;
    
    test('feature in your project', function () {
        // Arrange
        Analytics::fake([
            [
                'pageTitle' => 'Test Page',
                'activeUsers' => 10,
                'screenPageViews' => 20,
            ],
        ]);
    
        // Act
        $response = $this->actingAs($admin)->get('/analytics');
    
        // Assert
        $response->assertStatus(200);
    });
  4. Publish the analytics configuration

    main

    To customize settings like your property ID or credentials path, publish the configuration file to config/analytics.php using the following command:

    php artisan vendor:publish --tag="analytics-config"
  5. Grant permissions to your Analytics property

    main

    After creating your service account, you must grant it access to your GA4 property:

    1. Find Property ID: In Google Analytics, go to Settings > Property Settings and copy your Property ID. Add this to your .env as ANALYTICS_PROPERTY_ID.
    2. Add User: In Google Analytics, go to Property Access Management in the Admin section.
    3. Assign Role: Click the plus sign to add a new user. Use the client_email address found in your downloaded JSON credentials file. Assign the Analyst role.
  6. Configure analytics.php

    main

    The config/analytics.php file contains the following configuration keys:

    • property_id: The GA4 property ID (set via ANALYTICS_PROPERTY_ID in your .env).
    • service_account_credentials_json: The path to your Google Service Account JSON key file, or an array of credentials.
    • cache_lifetime_in_minutes: How long Google API responses should be cached. Set to 0 to disable caching.
    • cache: An array to configure the underlying Google client cache store. Supports store (e.g., 'file') and optional parameters like lifetime and prefix.
    return [
        'property_id' => env('ANALYTICS_PROPERTY_ID'),
        'service_account_credentials_json' => storage_path('app/analytics/service-account-credentials.json'),
        'cache_lifetime_in_minutes' => 60 * 24,
        'cache' => [
            'store' => 'file',
        ],
    ];
  7. Configure OrderBy for custom queries

    main

    When using the get method, you can sort results using an array of OrderBy objects.

    Example of sorting by date (ascending) and then by page views (descending):

    $orderBy = [
        OrderBy::dimension('date', true),
        OrderBy::metric('pageViews', false),
    ];
  8. Create a dimension filter for custom queries

    main

    Use FilterExpression to filter results based on dimension values.

    Example: Filtering for the exact event name 'click':

    use Google\Analytics\Data\V1beta\Filter;
    use Google\Analytics\Data\V1beta\FilterExpression;
    use Google\Analytics\Data\V1beta\Filter\StringFilter;
    use Google\Analytics\Data\V1beta\Filter\StringFilter\MatchType;
    
    $dimensionFilter = new FilterExpression([
        'filter' => new Filter([
            'field_name' => 'eventName',
            'string_filter' => new StringFilter([
                'match_type' => MatchType::EXACT,
                'value' => 'click',
            ]),
        ]),    
    ]);
  9. Create a metric filter for custom queries

    main

    Use FilterExpression to filter results after aggregation (similar to a SQL HAVING clause).

    Example: Filtering for eventCount greater than 3:

    use Google\Analytics\Data\V1beta\Filter;
    use Google\Analytics\Data\V1beta\FilterExpression;
    use Google\Analytics\Data\V1beta\Filter\NumericFilter;
    use Google\Analytics\Data\V1beta\NumericValue;
    use Google\Analytics\Data\V1beta\Filter\NumericFilter\Operation;
    
    $metricFilter = new FilterExpression([
        'filter' => new Filter([
            'field_name' => 'eventCount',
            'numeric_filter' => new NumericFilter([
                'operation' => Operation::GREATER_THAN,
                'value' => new NumericValue([
                    'int64_value' => 3,
                ]),
            ]),
        ]),    
    ]);
  10. Fetch visitors and page views by date

    main

    Retrieve a collection of visitors and page views broken down by date for a specific period. Each item in the returned Collection is an array containing:

    • date
    • activeUsers
    • screenPageViews
    • pageTitle
    public function fetchVisitorsAndPageViewsByDate(Period $period): Collection