Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Analytics Reports Laravel Package

spatie/analytics-reports

Abandoned Laravel 4 package by Spatie to retrieve Google Analytics data via service provider/facade. Includes config publishing and depends on google/apiclient and thujohn/analytics. For Laravel 5+, use spatie/laravel-analytics.

View on GitHub
Deep Wiki
Context7
## Getting Started

### Minimal Setup
1. **Installation** (Laravel 4 only):
   ```bash
   composer require spatie/analytics-reports

Publish the config file:

php artisan config:publish spatie/analytics-reports
  1. Configuration:

    • Set your Google Analytics viewId and apiKey in config/analytics-reports.php.
    • Ensure your Google API credentials are enabled for the Google Analytics API.
  2. First Use Case: Fetch basic metrics (e.g., pageviews) for a date range:

    use Spatie\AnalyticsReports\AnalyticsReportsFacade as Analytics;
    
    $data = Analytics::get('ga:pageviews', [
        'ids' => 'ga:YOUR_VIEW_ID',
        'start-date' => '30daysAgo',
        'end-date' => 'today',
    ]);
    

Implementation Patterns

Core Workflows

  1. Querying Data: Use the facade (Analytics::get()) to fetch metrics via Google Analytics' Core Reporting API. Example: Fetch sessions by traffic source:

    $sessions = Analytics::get('ga:sessions', [
        'dimensions' => 'ga:source,ga:medium',
        'sort' => '-ga:sessions',
    ]);
    
  2. Date Ranges: Leverage Google Analytics' date syntax (e.g., 7daysAgo, yesterday, 2023-01-01). Example: Compare weekly performance:

    $lastWeek = Analytics::get('ga:pageviews', [
        'ids' => 'ga:YOUR_VIEW_ID',
        'start-date' => '7daysAgo',
        'end-date' => '1daysAgo',
    ]);
    
  3. Integration with Laravel:

    • Cache responses to avoid hitting API limits:
      $cachedData = Cache::remember('analytics_pageviews', now()->addHours(1), function () {
          return Analytics::get('ga:pageviews', [...]);
      });
      
    • Use in controllers/views to display real-time metrics:
      return view('dashboard', ['pageviews' => $data]);
      
  4. Complex Reports: Combine metrics/dimensions for advanced insights:

    $report = Analytics::get('ga:pageviews,ga:bounces', [
        'dimensions' => 'ga:pagePath',
        'metrics' => 'ga:pageviews,ga:bounces',
        'filters' => 'ga:pagePath=@/blog',
    ]);
    

Gotchas and Tips

Pitfalls

  1. API Quotas:

    • Google Analytics API has strict quota limits.
    • Tip: Cache aggressively and implement rate-limiting in your app.
  2. Deprecated Package:

    • Critical: This package is abandoned (last release: 2016). Use spatie/laravel-analytics for Laravel 5+.
    • Workaround: Fork the repo and maintain it yourself if critical to your project.
  3. Laravel 4 Only:

    • Not compatible with Laravel 5+. Migrate to the newer package or manually adapt the code.
  4. Authentication Issues:

    • Ensure your apiKey is a Service Account Key (JSON) with https://www.googleapis.com/auth/analytics.readonly scope.
    • Debug Tip: Test API credentials via Google’s API Explorer.
  5. Date Format Strictness:

    • Google Analytics requires ISO 8601 dates (e.g., 2023-01-01). Relative dates (e.g., yesterday) work but may break in edge cases.

Debugging

  1. Enable Logging: Add this to config/analytics-reports.php to log raw API responses:

    'log_responses' => true,
    

    Check storage/logs/laravel.log for errors.

  2. Validate Queries: Use Google’s Query Explorer to test queries before implementing them in code.

  3. Common Errors:

    • Invalid Value: Check ids, metrics, or dimensions syntax.
    • User does not have any Google Analytics account: Verify viewId and permissions.
    • Daily Limit Exceeded: Implement exponential backoff or switch to a paid API plan.

Extension Points

  1. Custom Metrics/Dimensions: Extend the facade to support non-standard metrics by subclassing Spatie\AnalyticsReports\AnalyticsReportsServiceProvider:

    // app/Providers/AnalyticsServiceProvider.php
    namespace App\Providers;
    use Spatie\AnalyticsReports\AnalyticsReportsServiceProvider as BaseProvider;
    
    class AnalyticsServiceProvider extends BaseProvider {
        public function register() {
            parent::register();
            $this->app->alias('analytics', 'App\Services\CustomAnalytics');
        }
    }
    
  2. Batch Processing: Use Laravel queues to process large datasets asynchronously:

    Analytics::dispatch('ga:pageviews', [...])->onQueue('analytics');
    
  3. Local Testing: Mock the API responses in tests using Laravel’s HTTP mocking:

    $response = Analytics::get('ga:pageviews', [...]);
    Analytics::shouldReceive('get')->andReturn(['data' => 'mocked']);
    

---
**Note**: Due to the package's abandoned status, prioritize migrating to [`spatie/laravel-analytics`](https://github.com/spatie/laravel-analytics) for long-term projects. The above patterns assume continued use of this legacy package.
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
davejamesmiller/laravel-breadcrumbs
artisanry/parsedown
christhompsontldr/phpsdk
enqueue/dsn
bunny/bunny
enqueue/test
enqueue/null
enqueue/amqp-tools
milesj/emojibase
bower-asset/punycode
bower-asset/inputmask
bower-asset/jquery
bower-asset/yii2-pjax
laravel/nova
spatie/laravel-mailcoach
spatie/laravel-superseeder
laravel/liferaft
nst/json-test-suite
danielmiessler/sec-lists
jackalope/jackalope-transport