{"id":13396292,"url":"https://github.com/spatie/laravel-analytics","last_synced_at":"2025-05-14T08:04:18.699Z","repository":{"id":28549809,"uuid":"32067087","full_name":"spatie/laravel-analytics","owner":"spatie","description":"A Laravel package to retrieve pageviews and other data from Google Analytics","archived":false,"fork":false,"pushed_at":"2025-04-28T14:10:59.000Z","size":14782,"stargazers_count":3167,"open_issues_count":0,"forks_count":475,"subscribers_count":84,"default_branch":"main","last_synced_at":"2025-05-07T07:06:21.003Z","etag":null,"topics":["analytics","google","laravel","php","statistics"],"latest_commit_sha":null,"homepage":"https://freek.dev/2477-laravel-analytics-v5-with-support-for-ga4-has-been-released","language":"PHP","has_issues":false,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/spatie.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":null,"funding":".github/FUNDING.yml","license":"LICENSE.md","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null},"funding":{"custom":"https://spatie.be/open-source/support-us"}},"created_at":"2015-03-12T08:58:50.000Z","updated_at":"2025-05-01T19:59:09.000Z","dependencies_parsed_at":"2023-02-17T03:45:54.961Z","dependency_job_id":"74562bf9-7e8e-49c0-808d-dfc559953b07","html_url":"https://github.com/spatie/laravel-analytics","commit_stats":{"total_commits":385,"total_committers":71,"mean_commits":5.422535211267606,"dds":0.3974025974025974,"last_synced_commit":"81ca614e721ec34798c434502e64b7a158851d34"},"previous_names":[],"tags_count":65,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/spatie%2Flaravel-analytics","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/spatie%2Flaravel-analytics/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/spatie%2Flaravel-analytics/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/spatie%2Flaravel-analytics/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/spatie","download_url":"https://codeload.github.com/spatie/laravel-analytics/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":254101584,"owners_count":22014907,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["analytics","google","laravel","php","statistics"],"created_at":"2024-07-30T18:00:44.087Z","updated_at":"2025-05-14T08:04:18.643Z","avatar_url":"https://github.com/spatie.png","language":"PHP","funding_links":["https://spatie.be/open-source/support-us"],"categories":["Popular Packages","PHP","Paquetes utiles"],"sub_categories":[],"readme":"\u003cdiv align=\"left\"\u003e\n    \u003ca href=\"https://spatie.be/open-source?utm_source=github\u0026utm_medium=banner\u0026utm_campaign=laravel-analytics\"\u003e\n      \u003cpicture\u003e\n        \u003csource media=\"(prefers-color-scheme: dark)\" srcset=\"https://spatie.be/packages/header/laravel-analytics/html/dark.webp\"\u003e\n        \u003cimg alt=\"Logo for laravel-analytics\" src=\" https://spatie.be/packages/header/laravel-analytics/html/light.webp\" height=\"190\"\u003e\n      \u003c/picture\u003e\n    \u003c/a\u003e\n\n\u003ch1\u003eRetrieve data from Google Analytics\u003c/h1\u003e\n\n[![Latest Version](https://img.shields.io/github/release/spatie/laravel-analytics.svg?style=flat-square)](https://github.com/spatie/laravel-analytics/releases)\n[![MIT Licensed](https://img.shields.io/badge/license-MIT-brightgreen.svg?style=flat-square)](LICENSE.md)\n![Check \u0026 fix styling](https://github.com/spatie/laravel-analytics/workflows/Check%20\u0026%20fix%20styling/badge.svg)\n[![Total Downloads](https://img.shields.io/packagist/dt/spatie/laravel-analytics.svg?style=flat-square)](https://packagist.org/packages/spatie/laravel-analytics)\n    \n\u003c/div\u003e\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//fetch the most visited pages for today and the past week\nAnalytics::fetchMostVisitedPages(Period::days(7));\n\n//fetch 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://github-ads.s3.eu-central-1.amazonaws.com/laravel-analytics.jpg?t=1\" width=\"419px\" /\u003e](https://spatie.be/github-ad-click/laravel-analytics)\n\nWe invest a lot of resources into creating [best in class open source packages](https://spatie.be/open-source). You can support us by [buying one of our paid products](https://spatie.be/open-source/support-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://spatie.be/about-us). We publish all received postcards on [our virtual postcard wall](https://spatie.be/open-source/postcards).\n\n## Installation\n\nThis package can be installed through Composer.\n\n``` bash\ncomposer require spatie/laravel-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/analytics.php`\n\n```php\nreturn [\n\n    /*\n     * The property id of which you want to display data.\n     */\n    'property_id' =\u003e env('ANALYTICS_PROPERTY_ID'),\n\n    /*\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     */\n    'service_account_credentials_json' =\u003e storage_path('app/analytics/service-account-credentials.json'),\n\n    /*\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     */\n    'cache_lifetime_in_minutes' =\u003e 60 * 24,\n\n    /*\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     */\n    'cache' =\u003e [\n        'store' =\u003e '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://console.developers.google.com/apis) and select or create a project.\n\n![1](https://spatie.github.io/laravel-analytics/v5/1.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://spatie.github.io/laravel-analytics/v5/2.png)\n![3](https://spatie.github.io/laravel-analytics/v5/3.png)\n\nChoose enable to enable the API.\n![4](https://spatie.github.io/laravel-analytics/v5/4.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://spatie.github.io/laravel-analytics/v5/5.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://spatie.github.io/laravel-analytics/v5/6.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://spatie.github.io/laravel-analytics/v5/7.png)\n\nSelect \"JSON\" as the key type and click \"Create\" to download the JSON file.\n\n![8](https://spatie.github.io/laravel-analytics/v5/8.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://analytics.google.com/analytics) and are using the new GA4 properties.\n\nFirst you will need to know your property ID. In Analytics, go to Settings \u003e 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://spatie.github.io/laravel-analytics/v5/a1.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://spatie.github.io/laravel-analytics/v5/a2.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//retrieve visitors and page view data for the current day and the last seven days\n$analyticsData = Analytics::fetchVisitorsAndPageViews(Period::days(7));\n\n//retrieve 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()-\u003esubYear();\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 $limit = 10, array $orderBy = [], FilterExpression $dimensionFilter = null, 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://developers.google.com/analytics/devguides/reporting/data/v1/api-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://developers.google.com/analytics/devguides/reporting/data/v1/api-schema#dimensions).\n\n`int $limit`: the maximum number of results to return.\n\n`array $orderBy`: of OrderBy objects to sort the results by. \n\n`array $offset`: Defaults to 0, you can use this in combination with the $limit 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://cloud.google.com/php/docs/reference/analytics-data/latest/V1beta.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' =\u003e new Filter([\n        'field_name' =\u003e 'eventName',\n        'string_filter' =\u003e new StringFilter([\n            'match_type' =\u003e MatchType::EXACT,\n            'value' =\u003e '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://cloud.google.com/php/docs/reference/analytics-data/latest/V1beta.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' =\u003e new Filter([\n        'field_name' =\u003e 'eventCount',\n        'numeric_filter' =\u003e new NumericFilter([\n            'operation' =\u003e Operation::GREATER_THAN,\n            'value' =\u003e new NumericValue([\n                'int64_value' =\u003e 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    // Arrange\n    Analytics::fake();\n\n    // Act\n    $response = $this-\u003eactingAs($admin)-\u003eget('/analytics');\n\n    // Assert\n    $response-\u003eassertStatus(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    // Arrange\n    Analytics::fake([\n        [\n            'pageTitle' =\u003e 'Test Page',\n            'activeUsers' =\u003e 10,\n            'screenPageViews' =\u003e 20,\n        ],\n    ]);\n\n    // Act\n    $response = $this-\u003eactingAs($admin)-\u003eget('/analytics');\n\n    // Assert\n    $response-\u003eassertStatus(200);\n});\n```\n\n### Package tests\n\nRun the tests with:\n\n``` bash\nvendor/bin/pest\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://github.com/spatie/.github/blob/main/CONTRIBUTING.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://github.com/freekmurze)\n- [All Contributors](../../contributors)\n\nSpecial thanks to [Caneco](https://twitter.com/caneco) for the original logo.\n\n## License\n\nThe MIT License (MIT). Please see [License File](LICENSE.md) for more information.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fspatie%2Flaravel-analytics","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fspatie%2Flaravel-analytics","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fspatie%2Flaravel-analytics/lists"}