Search code examples
phplaravelgoogle-analyticsgoogle-analytics-apigoogle-analytics-data-api

DateRanges for Google Analytics Data API


I have been successfully running a runRealtimeReport function from Google Analytics Data API, but I am currently struggling to run a runReport function.

Here is my code which I try to use:

$client->runReport([
                    'entity' => ['property_Id' => config('app.ga.propertyID')],
                    'dateRanges' => [new DateRange(['startDate' => '28daysago']),
                        new DateRange(['endDate' => 'today'])],
                    'dimensions' => [new Dimension([
                        'name' => 'sessionSource'
                    ])
                    ],
                    'metrics' =>[
                        [new Metric([
                            'name' => 'activeUsers'
                        ])],
                    [new Metric([
                        'name' => 'sessions'
                    ])],
                    [new Metric([
                        'name' => 'engagedSessions'
                    ])],
                    [new Metric([
                        'name' => 'userEngagementDuration'
                    ])],
                    [new Metric([
                        'name' => 'eventsPerSession'
                    ])],
                    [new Metric([
                        'name' => 'engagementRate'
                    ])]
                ]]);

No matter how I try to pass the values for DateRange, the API constantly fails and throws the following error:

Invalid message property: startDate

I am using an idiomatic PHP client for this


Solution

  • You need to specify both the startDate and endDate in one Date Range. As written, you've specified the startDate and endDate in two separate date ranges. Please update to:

    'dateRanges' => [new DateRange(['start_date' => '28daysago',
                                   'end_date' => 'today'])],