Using spatie/laravel-analytics, how do I get page views for a specific pagePath?

Viewed 1481

I've just started looking at spatie/laravel-analytics, a package for getting data out of Google Analytics API. I'm a bit lost right now though as documentation seems thin... either that or I'm not searching for the right things.

What I want to do feels like it should be quite simple, get page views for each day over a period for a specific URL.

My current code block looks like this:

$analyticsData = Analytics::performQuery(
    Period::days(7),
    'ga:pageviews',
    [
        'metrics' => 'ga:pageviews',
        'dimensions' => 'ga:pagePath',
        'filters' => 'ga:pagePath==/pasta-recipes/lasagne/'
    ]
    
);
var_dump($analyticsData);

As always, any help appreciated.

2 Answers

In your case, just to replace this:

'dimensions' => 'ga:pagePath'

in:

'dimensions' => 'ga:date'

Output example:

enter image description here

use structure of function Analytics::fetchVisitorsAndPageViews(Period::days(7)); but use pagePath

 $response = Analytics::performQuery(
    Period::days(7),
    'ga:users,ga:pageviews',
    ['dimensions' => 'ga:date,ga:pagePath']
);
$analyticsData = collect($response['rows'] ?? [])->map(function (array $dateRow) {
    return [
        'date' => Carbon::createFromFormat('Ymd', $dateRow[0]),
        'url' => $dateRow[1],
        'visitors' => (int) $dateRow[2],
        'pageViews' => (int) $dateRow[3],
    ];
});
    dd($analyticsData);
Related