Usage | laravel-analytics-go | Spatie       

 SPATIE  

laravel-analytics-go
====================

spatie.be/open-source

  [Docs](https://spatie.be/docs)  [Laravel-analytics-go](https://spatie.be/docs/laravel-analytics-go/v1)  Usage

 Version   v1      

 Other versions for crawler [v1](https://spatie.be/docs/laravel-analytics-go/v1) 

  Usage    
- [ Introduction ](https://spatie.be/docs/laravel-analytics-go/v1/introduction)
- [ Support us ](https://spatie.be/docs/laravel-analytics-go/v1/support-us)
- [ Installation and setup ](https://spatie.be/docs/laravel-analytics-go/v1/installation-and-setup)
- [ Usage ](https://spatie.be/docs/laravel-analytics-go/v1/usage)
- [ Testing ](https://spatie.be/docs/laravel-analytics-go/v1/testing)
- [ Releasing ](https://spatie.be/docs/laravel-analytics-go/v1/releasing)
- [ Changelog ](https://spatie.be/docs/laravel-analytics-go/v1/changelog)

 Usage
=====

###  On this page 

1. [ Periods ](#content-periods)
2. [ Provided methods ](#content-provided-methods)
3. [ Realtime reports ](#content-realtime-reports)
4. [ Switching properties ](#content-switching-properties)
5. [ Raw Google requests ](#content-raw-google-requests)

When installation is done you can easily retrieve Analytics data. Nearly all methods return a slice of rows.

```
period, err := analytics.Days(7, date.Now(ctx))
if err != nil {
    return err
}
rows, err := analytics.From(ctx).FetchVisitorsAndPageViews(ctx, period)
```

Here `rows` contains `pageTitle`, `activeUsers` and `screenPageViews`. Pass a Laravel request, job, command or listener context as `ctx`.

Periods
-----------------------------------------------------------------------------

`Days`, `Months` and `Years` take an explicit `today` value. Use `date.Now(ctx)` with the property's timezone rather than relying on a server's local date. Both endpoints are included, so `Days(7, today)` covers eight calendar dates.

```
period, err := analytics.Months(6, date.Now(ctx))
```

Months and years clamp to the last valid date of shorter months. For example, one month before March 31, 2024 is February 29, 2024. This deliberate difference avoids PHP/Go month overflow into March.

For more control, pass a start date and an end date:

```
period, err := analytics.Create(startDate, endDate)
```

Reversed dates return an error. Use dates in the property's timezone. Times of day are omitted from the Google request. Returned `date` values are calendar dates represented at UTC midnight, not event timestamps.

Provided methods
--------------------------------------------------------------------------------------------------------

All methods take `context.Context` first, then a `Period`, and return `([]analytics.Row, error)`. Optional report settings follow the period. Errors never become empty successful reports.

### Visitors and page views

```
rows, err := client.FetchVisitorsAndPageViews(ctx, period)
```

Each row holds `activeUsers`, `screenPageViews` and `pageTitle`. The default limit is 10.

### Visitors and page views by date

```
rows, err := client.FetchVisitorsAndPageViewsByDate(ctx, period)
```

Each row holds `date`, `activeUsers`, `screenPageViews` and `pageTitle`. Dates sort descending, matching PHP. The default limit is 10.

### Total visitors and pageviews

```
rows, err := client.FetchTotalVisitorsAndPageViews(ctx, period)
```

Each row holds `date`, `activeUsers` and `screenPageViews`. Dates sort descending. The default limit is 20. Despite its name this returns daily rows, not one period-wide total. Daily active users are not additive. To retrieve distinct users for the whole period, call `Get` with no dimensions.

### Most visited pages

```
rows, err := client.FetchMostVisitedPages(ctx, period, analytics.Limit(20))
```

Each row holds `fullPageUrl`, `pageTitle` and `screenPageViews`, sorted by pageviews descending. The default limit is 20. Titles and URLs remain separate combinations. Google's `fullPageUrl` can omit the scheme.

### Top referrers

```
rows, err := client.FetchTopReferrers(ctx, period)
```

Each row holds `screenPageViews` and `pageReferrer`, sorted by pageviews descending. The default limit is 20. Empty referrers are preserved.

### User types

```
rows, err := client.FetchUserTypes(ctx, period)
```

Each row holds `activeUsers` and `newVsReturning`, which can be `new`, `returning`, or a Google label such as `(not set)`. The default limit is 10.

### Top browsers

```
rows, err := client.FetchTopBrowsers(ctx, period)
```

Each row holds `screenPageViews` and `browser`, sorted by pageviews descending. The default limit is 10.

### Top countries

```
rows, err := client.FetchTopCountries(ctx, period)
```

Each row holds `screenPageViews` and `country`, sorted by pageviews descending. The default limit is 10.

### Top operating systems

```
rows, err := client.FetchTopOperatingSystems(ctx, period)
```

Each row holds `screenPageViews` and `operatingSystem`, sorted by pageviews descending. The default limit is 10.

### All other Google Analytics queries

For all other queries use `Get`:

```
rows, err := client.Get(ctx, period, analytics.Query{
    Metrics: []string{"activeUsers", "screenPageViews"},
    Dimensions: []string{"country", "city"},
    Limit: 100,
    Offset: 20,
    OrderBy: []*analyticsdata.OrderBy{
        analytics.DimensionOrder("city", false),
        analytics.MetricOrder("screenPageViews", true),
    },
    KeepEmptyRows: true,
})
```

Import `google.golang.org/api/analyticsdata/v1beta` as `analyticsdata` for Google types.

- `Metrics` lists the [metrics](https://developers.google.com/analytics/devguides/reporting/data/v1/api-schema#metrics) to retrieve. At least one is required.
- `Dimensions` lists the [dimensions](https://developers.google.com/analytics/devguides/reporting/data/v1/api-schema#dimensions) to group by. Omit them for period-wide aggregates.
- `Limit` is the maximum rows in a single request. Zero defaults to 10. Limits above 250,000 or below zero return an error.
- `Offset` is zero-based pagination. Use it with a limit and stable ordering to fetch another page. Data can change between requests.
- `OrderBy` lists sorting rules in precedence order. `true` means descending.
- `KeepEmptyRows` includes rows with all-zero metrics if a filter does not remove them.

Named reports accept `analytics.Limit(n)`, `analytics.Offset(n)` and any `func(*analytics.Query)` callback, so filters and order rules are customizable there too.

`DimensionFilter` and `MetricFilter` accept Google's complete `FilterExpression` type, including nested AND/OR/NOT groups. Dimension filters run before aggregation. Metric filters act after aggregation, like SQL's HAVING clause.

```
query.DimensionFilter = &analyticsdata.FilterExpression{
    Filter: &analyticsdata.Filter{
        FieldName: "eventName",
        StringFilter: &analyticsdata.StringFilter{MatchType: "EXACT", Value: "click"},
    },
}
query.MetricFilter = &analyticsdata.FilterExpression{
    Filter: &analyticsdata.Filter{
        FieldName: "eventCount",
        NumericFilter: &analyticsdata.NumericFilter{
            Operation: "GREATER_THAN",
            Value: &analyticsdata.NumericValue{Int64Value: 3},
        },
    },
}
```

Column names must be nonempty and unique. Known counts (`visitors`, `pageViews`, `activeUsers`, `newUsers`, `screenPageViews`, `active1DayUsers`, `active7DayUsers`, `active28DayUsers`) become nonnegative `int64` values. Malformed counts, dates and row shapes return errors. Unknown columns, including decimal metrics, remain strings.

Realtime reports
--------------------------------------------------------------------------------------------------------

```
rows, err := client.GetRealtime(ctx,
    analytics.MinuteRange{StartMinutesAgo: 29, EndMinutesAgo: 0},
    analytics.Query{Metrics: []string{"activeUsers"}, Dimensions: []string{"country"}},
)
```

Minutes are inclusive, from the older start to the newer end. High-level realtime queries require `0 <= end <= start <= 29` for standard properties. They support filters, order and a limit, but reject offsets and `KeepEmptyRows` rather than silently ignoring them. Use a short cache lifetime or disable caching when freshness matters.

Switching properties
--------------------------------------------------------------------------------------------------------------------

```
other, err := client.WithPropertyID("987654321")
```

This returns a separate client sharing authentication and cache infrastructure, with property-specific cache entries. It does not mutate the original app-scoped client. Invalid property IDs return an error. `PropertyID()` reads the current value.

Raw Google requests
-----------------------------------------------------------------------------------------------------------------

`RunReport(ctx, *analyticsdata.RunReportRequest)` and `RunRealtimeReport(ctx, *analyticsdata.RunRealtimeReportRequest)` use this client's property, cache serialized responses, and return Google's response structs. These preserve API response data such as totals, row count and quota fields, but do not retain HTTP response headers through serialization. They do not cast values or apply high-level query validation. Use them for Google options beyond the high-level interface.

`AnalyticsService()` exposes the underlying SDK service. Calls made directly on it bypass package caching and casting. Configure the service before concurrent use. Raw methods are not supported by `Fake`.

Go has no runtime macros. Compose or embed `*analytics.Client` in your own application service when adding methods instead of modifying a global facade.

 A good
match?
-------------

### What we do best

- All things Laravel
- Custom frontend components
- Building APIs
- AI-powered features
- Simplifying things
- Clean solutions
- Integrating services

### Not our cup of tea

- WordPress themes
- Cutting corners
- Free mockups to win a job
- "Just execute the briefing"

 In short: we'd like to be a **substantial part** of your project.

 [ Get in touch via email ](mailto:info@spatie.be?subject=A%20good%20match%21&body=Tell%20us%20as%20much%20as%20you%20can%20about%0A-%20your%20online%20project%0A-%20your%20planning%0A-%20your%20budget%0A-%20%E2%80%A6%0A%0AAnything%20that%20helps%20us%20to%20start%20straightforward%21)
