[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"project-8551":3},{"id":4,"name":5,"fullName":6,"owner":7,"repo":5,"description":8,"homepage":9,"htmlUrl":10,"language":11,"languages":10,"totalLinesOfCode":10,"stars":12,"forks":13,"watchers":14,"openIssues":15,"contributorsCount":15,"subscribersCount":15,"size":15,"stars1d":15,"stars7d":15,"stars30d":16,"stars90d":15,"forks30d":15,"starsTrendScore":15,"compositeScore":17,"rankGlobal":10,"rankLanguage":10,"license":18,"archived":19,"fork":19,"defaultBranch":20,"hasWiki":19,"hasPages":21,"topics":22,"createdAt":10,"pushedAt":10,"updatedAt":28,"readmeContent":29,"aiSummary":30,"trendingCount":15,"starSnapshotCount":15,"syncStatus":31,"lastSyncTime":32,"discoverSource":33},8551,"laravel-analytics","spatie\u002Flaravel-analytics","spatie","A Laravel package to retrieve pageviews and other data from Google Analytics","https:\u002F\u002Ffreek.dev\u002F2477-laravel-analytics-v5-with-support-for-ga4-has-been-released",null,"PHP",3237,474,84,0,1,60.13,"MIT License",false,"main",true,[23,24,25,26,27],"analytics","google","laravel","php","statistics","2026-06-12 04:00:40","\u003Cdiv align=\"left\">\n    \u003Ca href=\"https:\u002F\u002Fspatie.be\u002Fopen-source?utm_source=github&utm_medium=banner&utm_campaign=laravel-analytics\">\n      \u003Cpicture>\n        \u003Csource media=\"(prefers-color-scheme: dark)\" srcset=\"https:\u002F\u002Fspatie.be\u002Fpackages\u002Fheader\u002Flaravel-analytics\u002Fhtml\u002Fdark.webp\">\n        \u003Cimg alt=\"Logo for laravel-analytics\" src=\"https:\u002F\u002Fspatie.be\u002Fpackages\u002Fheader\u002Flaravel-analytics\u002Fhtml\u002Flight.webp\">\n      \u003C\u002Fpicture>\n    \u003C\u002Fa>\n\n\u003Ch1>Retrieve data from Google Analytics\u003C\u002Fh1>\n\n[![Latest Version](https:\u002F\u002Fimg.shields.io\u002Fgithub\u002Frelease\u002Fspatie\u002Flaravel-analytics.svg?style=flat-square)](https:\u002F\u002Fgithub.com\u002Fspatie\u002Flaravel-analytics\u002Freleases)\n[![MIT Licensed](https:\u002F\u002Fimg.shields.io\u002Fbadge\u002Flicense-MIT-brightgreen.svg?style=flat-square)](LICENSE.md)\n![Check & fix styling](https:\u002F\u002Fgithub.com\u002Fspatie\u002Flaravel-analytics\u002Fworkflows\u002FCheck%20&%20fix%20styling\u002Fbadge.svg)\n[![Total Downloads](https:\u002F\u002Fimg.shields.io\u002Fpackagist\u002Fdt\u002Fspatie\u002Flaravel-analytics.svg?style=flat-square)](https:\u002F\u002Fpackagist.org\u002Fpackages\u002Fspatie\u002Flaravel-analytics)\n    \n\u003C\u002Fdiv>\n\nUsing this package you can easily retrieve data from Google Analytics.\n\nHere are a few examples of the provided methods:\n\n```php\nuse Spatie\\Analytics\\Facades\\Analytics;\nuse Spatie\\Analytics\\Period;\n\n\u002F\u002Ffetch the most visited pages for today and the past week\nAnalytics::fetchMostVisitedPages(Period::days(7));\n\n\u002F\u002Ffetch visitors and page views for the past week\nAnalytics::fetchVisitorsAndPageViews(Period::days(7));\n```\n\nMost methods will return an `\\Illuminate\\Support\\Collection` object containing the results.\n\n## Support us\n\n[\u003Cimg src=\"https:\u002F\u002Fgithub-ads.s3.eu-central-1.amazonaws.com\u002Flaravel-analytics.jpg?t=1\" width=\"419px\" \u002F>](https:\u002F\u002Fspatie.be\u002Fgithub-ad-click\u002Flaravel-analytics)\n\nWe invest a lot of resources into creating [best in class open source packages](https:\u002F\u002Fspatie.be\u002Fopen-source). You can support us by [buying one of our paid products](https:\u002F\u002Fspatie.be\u002Fopen-source\u002Fsupport-us).\n\nWe highly appreciate you sending us a postcard from your hometown, mentioning which of our package(s) you are using. You'll find our address on [our contact page](https:\u002F\u002Fspatie.be\u002Fabout-us). We publish all received postcards on [our virtual postcard wall](https:\u002F\u002Fspatie.be\u002Fopen-source\u002Fpostcards).\n\n## Installation\n\nThis package can be installed through Composer.\n\n``` bash\ncomposer require spatie\u002Flaravel-analytics\n```\n\nOptionally, you can publish the config file of this package with this command:\n\n``` bash\nphp artisan vendor:publish --tag=\"analytics-config\"\n```\n\nThe following config file will be published in `config\u002Fanalytics.php`\n\n```php\nreturn [\n\n    \u002F*\n     * The property id of which you want to display data.\n     *\u002F\n    'property_id' => env('ANALYTICS_PROPERTY_ID'),\n\n    \u002F*\n     * Path to the client secret json file. Take a look at the README of this package\n     * to learn how to get this file. You can also pass the credentials as an array\n     * instead of a file path.\n     *\u002F\n    'service_account_credentials_json' => storage_path('app\u002Fanalytics\u002Fservice-account-credentials.json'),\n\n    \u002F*\n     * The amount of minutes the Google API responses will be cached.\n     * If you set this to zero, the responses won't be cached at all.\n     *\u002F\n    'cache_lifetime_in_minutes' => 60 * 24,\n\n    \u002F*\n     * Here you may configure the \"store\" that the underlying Google_Client will\n     * use to store it's data.  You may also add extra parameters that will\n     * be passed on setCacheConfig (see docs for google-api-php-client).\n     *\n     * Optional parameters: \"lifetime\", \"prefix\"\n     *\u002F\n    'cache' => [\n        'store' => 'file',\n    ],\n];\n```\n\n## How to obtain the credentials to communicate with Google Analytics\n\n### Getting credentials\n\nThe first thing you’ll need to do is to get some credentials to use Google API’s. I’m assuming that you’ve already created a Google account and are signed in. Head over to [Google API’s site](https:\u002F\u002Fconsole.developers.google.com\u002Fapis) and select or create a project.\n\n![1](https:\u002F\u002Fspatie.github.io\u002Flaravel-analytics\u002Fv5\u002F1.png)\n\nNext up we must specify which API’s the project may consume. Go to the API Library and search for \"Google Analytics Data API\".\n\n![2](https:\u002F\u002Fspatie.github.io\u002Flaravel-analytics\u002Fv5\u002F2.png)\n![3](https:\u002F\u002Fspatie.github.io\u002Flaravel-analytics\u002Fv5\u002F3.png)\n\nChoose enable to enable the API.\n![4](https:\u002F\u002Fspatie.github.io\u002Flaravel-analytics\u002Fv5\u002F4.png)\n\nNow that you’ve created a project that has access to the Analytics API it’s time to download a file with these credentials. Click \"Credentials\" in the sidebar. You’ll want to create a \"Service account key\".\n![5](https:\u002F\u002Fspatie.github.io\u002Flaravel-analytics\u002Fv5\u002F5.png)\n\nOn the next screen you can give the service account a name. You can name it anything you’d like. In the service account id you’ll see an email address. We’ll use this email address later on in this guide.\n\n![6](https:\u002F\u002Fspatie.github.io\u002Flaravel-analytics\u002Fv5\u002F6.png)\n\nGo to the details screen of your created service account and select \"keys\", from the \"Add key\" dropdown select \"Create new key\". \n\n![7](https:\u002F\u002Fspatie.github.io\u002Flaravel-analytics\u002Fv5\u002F7.png)\n\nSelect \"JSON\" as the key type and click \"Create\" to download the JSON file.\n\n![8](https:\u002F\u002Fspatie.github.io\u002Flaravel-analytics\u002Fv5\u002F8.png)\n\nSave the json inside your Laravel project at the location specified in the `service_account_credentials_json` key of the config file of this package. Because the json file contains potentially sensitive information I don't recommend committing it to your git repository.\n\n### Granting permissions to your Analytics property\n\nI'm assuming that you've already created a Analytics account on the [Analytics site](https:\u002F\u002Fanalytics.google.com\u002Fanalytics) and are using the new GA4 properties.\n\nFirst you will need to know your property ID. In Analytics, go to Settings > Property Settings. Here you will be able to copy your property ID. Use this value for the `ANALYTICS_PROPERTY_ID` key in your .env file.\n\n![a1](https:\u002F\u002Fspatie.github.io\u002Flaravel-analytics\u002Fv5\u002Fa1.png)\n\nNow we will need to give access to the service account you created. Go to \"Property Access Management\" in the Admin-section of the property.\nClick the plus sign in the top right corner to add a new user.\n\nOn this screen you can grant access to the email address found in the `client_email` key from the json file you download in the previous step. Analyst role is enough.\n\n![a2](https:\u002F\u002Fspatie.github.io\u002Flaravel-analytics\u002Fv5\u002Fa2.png)\n\n## Usage\n\nWhen the installation is done you can easily retrieve Analytics data. Nearly all methods will return an `Illuminate\\Support\\Collection`-instance.\n\n\nHere are a few examples using periods\n\n```php\nuse Spatie\\Analytics\\Facades\\Analytics;\n\n\u002F\u002Fretrieve visitors and page view data for the current day and the last seven days\n$analyticsData = Analytics::fetchVisitorsAndPageViews(Period::days(7));\n\n\u002F\u002Fretrieve visitors and page views since the 6 months ago\n$analyticsData = Analytics::fetchVisitorsAndPageViews(Period::months(6));\n```\n\n`$analyticsData` is a `Collection` in which each item is an array that holds keys `date`, `visitors` and `pageViews`\n\nIf you want to have more control over the period you want to fetch data for, you can pass a `startDate` and an `endDate` to the period object.\n\n```php\n$startDate = Carbon::now()->subYear();\n$endDate = Carbon::now();\n\nPeriod::create($startDate, $endDate);\n```\n\n## Provided methods\n\n### Visitors and page views\n\n```php\npublic function fetchVisitorsAndPageViews(Period $period): Collection\n```\n\nThe function returns a `Collection` in which each item is an array that holds keys `activeUsers`, `screenPageViews` and `pageTitle`.\n\n### Visitors and page views by date\n\n```php\npublic function fetchVisitorsAndPageViewsByDate(Period $period): Collection\n```\n\nThe function returns a `Collection` in which each item is an array that holds keys `date`, `activeUsers`, `screenPageViews` and `pageTitle`.\n\n### Total visitors and pageviews\n\n```php\npublic function fetchTotalVisitorsAndPageViews(Period $period): Collection\n```\n\nThe function returns a `Collection` in which each item is an array that holds keys `date`, `date`, `visitors`, and `pageViews`.\n\n### Most visited pages\n\n```php\npublic function fetchMostVisitedPages(Period $period, int $maxResults = 20): Collection\n```\n\nThe function returns a `Collection` in which each item is an array that holds keys `fullPageUrl`, `pageTitle` and `screenPageViews`.\n\n### Top referrers\n\n```php\npublic function fetchTopReferrers(Period $period, int $maxResults = 20): Collection\n```\n\nThe function returns a `Collection` in which each item is an array that holds keys `screenPageViews` and `pageReferrer`.\n\n### User Types\n\n```php\npublic function fetchUserTypes(Period $period): Collection\n```\n\nThe function returns a `Collection` in which each item is an array that holds keys `activeUsers` and `newVsReturning` which can equal to `new` or `returning`.\n\n### Top browsers\n\n```php\npublic function fetchTopBrowsers(Period $period, int $maxResults = 10): Collection\n```\n\nThe function returns a `Collection` in which each item is an array that holds keys `screenPageViews` and `browser`.\n\n### Top countries\n\n```php\npublic function fetchTopCountries(Period $period, int $maxResults = 10): Collection\n```\n\nThe function returns a `Collection` in which each item is an array that holds keys `screenPageViews` and `country`.\n\n### Top operating systems\n\n```php\npublic function fetchTopOperatingSystems(Period $period, int $maxResults = 10): Collection\n```\n\nThe function returns a `Collection` in which each item is an array that holds keys `screenPageViews` and `operatingSystem`.\n\n### All other Google Analytics queries\n\nFor all other queries you can use the `get` function.\n\n```php\npublic function get(Period $period, array $metrics, array $dimensions = [], int $maxResults = 10, array $orderBy = [], int $offset = 0, ?FilterExpression $dimensionFilter = null, bool $keepEmptyRows = false, ?FilterExpression $metricFilter = null): Collection\n```\n\nHere's some extra info on the arguments you can pass:\n\n`Period $period`: a Spatie\\Analytics\\Period object to indicate that start and end date for your query.\n\n`array $metrics`: an array of metrics to retrieve. You can find a list of all metrics [here](https:\u002F\u002Fdevelopers.google.com\u002Fanalytics\u002Fdevguides\u002Freporting\u002Fdata\u002Fv1\u002Fapi-schema#metrics).\n\n`array $dimensions`: an array of dimensions to group the results by. You can find a list of all dimensions [here](https:\u002F\u002Fdevelopers.google.com\u002Fanalytics\u002Fdevguides\u002Freporting\u002Fdata\u002Fv1\u002Fapi-schema#dimensions).\n\n`int $maxResults`: the maximum number of results to return.\n\n`array $orderBy`: of OrderBy objects to sort the results by. \n\n`init $offset`: Defaults to 0, you can use this in combination with the $maxResults param to have pagination.\n\n`bool $keepEmptyRows`: If false or unspecified, each row with all metrics equal to 0 will not be returned. If true, these rows will be returned if they are not separately removed by a filter.\n\nFor example:\n```php\n$orderBy = [\n    OrderBy::dimension('date', true),\n    OrderBy::metric('pageViews', false),\n];\n```\n\n`FilterExpression $dimensionFilter`: filter the result to include only specific dimension values. You can find more details [here](https:\u002F\u002Fcloud.google.com\u002Fphp\u002Fdocs\u002Freference\u002Fanalytics-data\u002Flatest\u002FV1beta.RunReportRequest).\n\nFor example:\n```php\nuse Google\\Analytics\\Data\\V1beta\\Filter;\nuse Google\\Analytics\\Data\\V1beta\\FilterExpression;\nuse Google\\Analytics\\Data\\V1beta\\Filter\\StringFilter;\nuse Google\\Analytics\\Data\\V1beta\\Filter\\StringFilter\\MatchType;\n\n$dimensionFilter = new FilterExpression([\n    'filter' => new Filter([\n        'field_name' => 'eventName',\n        'string_filter' => new StringFilter([\n            'match_type' => MatchType::EXACT,\n            'value' => 'click',\n        ]),\n    ]),    \n]);\n```\n\n`FilterExpression $metricFilter`: filter applied after aggregating the report's rows, similar to SQL having-clause. Dimensions cannot be used in this filter. You can find more details [here](https:\u002F\u002Fcloud.google.com\u002Fphp\u002Fdocs\u002Freference\u002Fanalytics-data\u002Flatest\u002FV1beta.RunReportRequest).\n\nFor example:\n```php\nuse Google\\Analytics\\Data\\V1beta\\Filter;\nuse Google\\Analytics\\Data\\V1beta\\FilterExpression;\nuse Google\\Analytics\\Data\\V1beta\\Filter\\NumericFilter;\nuse Google\\Analytics\\Data\\V1beta\\NumericValue;\nuse Google\\Analytics\\Data\\V1beta\\Filter\\NumericFilter\\Operation;\n\n$metricFilter = new FilterExpression([\n    'filter' => new Filter([\n        'field_name' => 'eventCount',\n        'numeric_filter' => new NumericFilter([\n            'operation' => Operation::GREATER_THAN,\n            'value' => new NumericValue([\n                'int64_value' => 3,\n            ]),\n        ]),\n    ]),    \n]);\n```\n\n## Testing\n\n### Faking\n\nTo fake calls within the package in your own project you can use the `fake` method on the `Spatie\\Analytics\\Facades\\Analytics` facade.\n\nFor example:\n\n```php\n\u003C?php\n\nuse Spatie\\Analytics\\Facades\\Analytics;\n\ntest('feature in your project', function () {\n    \u002F\u002F Arrange\n    Analytics::fake();\n\n    \u002F\u002F Act\n    $response = $this->actingAs($admin)->get('\u002Fanalytics');\n\n    \u002F\u002F Assert\n    $response->assertStatus(200);\n});\n```\n\nYou can also specify the expected result either as an array or `Illuminate\\Support\\Collection` to be returned when a method is called on the facade.\n\nFor example:\n\n```php\n\u003C?php\n\nuse Spatie\\Analytics\\Facades\\Analytics;\n\ntest('feature in your project', function () {\n    \u002F\u002F Arrange\n    Analytics::fake([\n        [\n            'pageTitle' => 'Test Page',\n            'activeUsers' => 10,\n            'screenPageViews' => 20,\n        ],\n    ]);\n\n    \u002F\u002F Act\n    $response = $this->actingAs($admin)->get('\u002Fanalytics');\n\n    \u002F\u002F Assert\n    $response->assertStatus(200);\n});\n```\n\n### Package tests\n\nRun the tests with:\n\n``` bash\nvendor\u002Fbin\u002Fpest\n```\n\n## Changelog\n\nPlease see [CHANGELOG](CHANGELOG.md) for more information what has changed recently.\n\n## Contributing\n\nPlease see [CONTRIBUTING](https:\u002F\u002Fgithub.com\u002Fspatie\u002F.github\u002Fblob\u002Fmain\u002FCONTRIBUTING.md) for details.\n\n## Security\n\nIf you've found a bug regarding security please mail [security@spatie.be](mailto:security@spatie.be) instead of using the issue tracker.\n\n## Credits\n\n- [Freek Van der Herten](https:\u002F\u002Fgithub.com\u002Ffreekmurze)\n- [All Contributors](..\u002F..\u002Fcontributors)\n\nSpecial thanks to [Caneco](https:\u002F\u002Ftwitter.com\u002Fcaneco) for the original logo.\n\n## License\n\nThe MIT License (MIT). Please see [License File](LICENSE.md) for more information.\n","spatie\u002Flaravel-analytics 是一个用于从 Google Analytics 获取页面浏览量及其他数据的 Laravel 扩展包。它支持通过简单的方法调用来获取如最常访问页面、访客数量和页面浏览量等信息，并将结果以 `\\Illuminate\\Support\\Collection` 对象的形式返回，便于进一步处理。该扩展包基于 PHP 开发，适用于需要集成 Google Analytics 数据到 Laravel 应用中的场景，比如网站管理员希望直接在后台查看关键指标而无需离开应用界面的情况。",2,"2026-06-11 03:18:35","top_language"]