Filament Google Analytics

repository·main·Indexed 42 days ago

https://github.com/bezhansalleh/filament-google-analytics

A Google Analytics (GA4) integration for Filament Panels that provides pre-built widgets to display analytics data directly within the Filament admin interface. Includes widgets for page views, visitors, active users, sessions, and country-based data, as well as a dedicated dashboard and the GAStatsBuilder for creating custom statistics widgets.

Tokens
4.5K
Snippets
17
Records
20
Agent score
54%

What's inside Filament Google Analytics

  1. Register the Google Analytics Plugin in Filament

    main

    Add the GoogleAnalyticsPlugin to your Filament Panel provider configuration:

    public function panel(Panel $panel): Panel
    {
        return $panel
            ->plugins([
                \BezhanSalleh\GoogleAnalytics\GoogleAnalyticsPlugin::make()
            ]);
    }
    public function panel(Panel $panel): Panel
    {
        return $panel
            ->plugins([
                ...
                \BezhanSalleh\GoogleAnalytics\GoogleAnalyticsPlugin::make()
            ]);
    }
  2. Use Google Analytics widgets in Filament

    main

    All widgets are available to be used in Filament pages or resources.

    Enabling widgets on the default Dashboard

    To show widgets on the default Filament dashboard, you must publish the configuration and set the filament_dashboard option to true for each specific widget you want to enable in config/google-analytics.php.

    To publish the config:

    php artisan vendor:publish --tag=google-analytics-config

    Available Widgets

    Import the Widgets class to access the following:

    • Widgets\ PageViewsWidget::class
    • Widgets\VisitorsWidget::class
    • Widgets\ActiveUsersOneDayWidget::class
    • Widgets\ActiveUsersSevenDayWidget::class
    • Widgets\ActiveUsersTwentyEightDayWidget::class
    • Widgets\SessionsWidget::class
    • Widgets\SessionsByCountryWidget::class
    • Widgets\SessionsDurationWidget::class
    • Widgets\SessionsByDeviceWidget::class
    • Widgets\MostVisitedPagesWidget::class
    • Widgets\TopReferrersListWidget::class
  3. Install filament-google-analytics

    main

    Install the package into your Laravel application using Composer:

    composer require bezhansalleh/filament-google-analytics

    Credentials Setup

    1. Obtain Google Analytics credentials following Spatie's Laravel Google Analytics package instructions.
    2. Place the service account JSON file at yourapp/storage/app/analytics/service-account-credentials.json.
    3. Add your Google Analytics Property ID to your .env file:
    ANALYTICS_PROPERTY_ID=
  4. Configure Tailwind CSS for Filament Custom Themes

    main

    If you are using a custom theme in Filament, you must add the plugin's resources to your theme's CSS file so Tailwind can scan them for classes:

    @source '../../../../vendor/bezhansalleh/filament-google-analytics/resources/views/**/*';
    @source '../../../../vendor/bezhansalleh/filament-google-analytics/src/{Widgets,Support}/*';
  5. Resolve GAStats from different response types

    main

    The resolve() method handles two primary types of input via usingResponse():

    1. GoogleAnalytics Instance: If the response is an instance of GoogleAnalytics, the builder extracts trajectory values (current vs previous), descriptions, icons, colors, and chart data to create a rich GAStats object.
    2. Raw Data Array: If the response is a standard data array, the builder looks for a results key, treats the last element as the current value, and generates a chart based on the full results array.
  6. Create a custom Google Analytics dashboard page

    main

    If you want to customize the dashboard (e.g., change navigation labels, groups, or specific widget selection), the recommended approach is to disable the default dashboard and create a custom Filament page.

    1. Generate a new page:
    php artisan filament:page MyCustomDashboardPage
    1. Register the desired widgets in getHeaderWidgets() or getFooterWidgets():
    <?php
    
    namespace App\Filament\Pages;
    
    use Filament\Pages\Page;
    use BezhanSalleh\GoogleAnalytics\Widgets;
    
    class MyCustomDashboardPage extends Page
    {
        protected static ?string $navigationIcon = 'heroicon-o-document-text';
    
        protected static string $view = 'filament.pages.my-custom-dashboard-page';
    
        protected function getHeaderWidgets(): array
        {
            return [
                Widgets\PageViewsWidget::class,
                Widgets\VisitorsWidget::class,
                // Add other widgets here...
            ];
        }
    }
    <?php
    
    namespace App\Filament\Pages;
    
    use Filament\Pages\Page;
    use BezhanSalleh\GoogleAnalytics\Widgets;
    
    class MyCustomDashboardPage extends Page
    {
        protected static ?string $navigationIcon = 'heroicon-o-document-text';
    
        protected static string $view = 'filament.pages.my-custom-dashboard-page';
    
        protected function getHeaderWidgets(): array
        {
            return [
                Widgets\PageViewsWidget::class,
                Widgets\VisitorsWidget::class,
                Widgets\ActiveUsersOneDayWidget::class,
                Widgets\ActiveUsersSevenDayWidget::class,
                Widgets\ActiveUsersTwentyEightDayWidget::class,
                Widgets\SessionsWidget::class,
                Widgets\SessionsByCountryWidget::class,
                Widgets\SessionsDurationWidget::class,
                Widgets\SessionsByDeviceWidget::class,
    n            Widgets\MostVisitedPagesWidget::class,
                Widgets\TopReferrersListWidget::class,
            ];
        }
    }
  7. Configure the Google Analytics Dashboard visibility and icon

    main

    The Google Analytics dashboard page behavior is controlled via the google-analytics configuration file. You can customize the navigation icon and determine if the dashboard is visible.

    • Navigation Icon: Set the dashboard_icon key to any Heroicon name (e.g., heroicon-m-chart-bar).
    • Dashboard Visibility: The dashboard's visibility is controlled by the dedicated_dashboard configuration key. If this is set to false, the canView() method will return false, preventing the page from being accessed.
    // Example configuration in config/google-analytics.php
    return [
        'dashboard_icon' => 'heroicon-m-presentation-chart-line',
        'dedicated_dashboard' => true,
    ];
  8. Configure filters and options in GAStatsBuilder

    main

    When building statistics, you can attach selection filters and options to the builder using withSelectFilter(). This is useful for allowing users to filter the displayed data (e.g., by dimension or date range) within the UI.

    • $options: An array of int|string => string representing the selection choices.
    • $filter: A string representing the specific filter to apply.
    $builder = GAStatsBuilder::make('Page Views')
        ->usingResponse($response)
        ->withSelectFilter(['daily' => 'Daily', 'weekly' => 'Weekly'], 'dimension_filter_key');
    
    $gaStats = $builder->resolve();
  9. Use GAStats to create custom statistics widgets

    main

    The GAStats class extends Filament's Stat class and is used to represent Google Analytics (GA4) statistics within a StatsOverviewWidget. You can use the select() method to specify which metrics/dimensions to retrieve and which filter to apply.

    To configure a GAStats instance, call select() with two parameters:

    1. $options: An associative array where keys are the metric/dimension identifiers and values are the labels to display.
    2. $filter: (Optional) A string representing the filter to apply to the data.

    This class provides getFilter() and getOptions() methods to retrieve the configured state.

    use BezhanSalleh\GoogleAnalytics\Support\GAStats;
    
    GAStats::make()
        ->select([
            'activeUsers' => 'Active Users',
            'sessions' => 'Sessions',
        ], 'some-filter-string');
  10. Construct GAStats using GAStatsBuilder

    main

    The GAStatsBuilder is used to transform raw Google Analytics data or GoogleAnalytics response objects into a structured GAStats object suitable for display in Filament. You can initiate the builder using the make() static method, providing a heading and an optional type.

    To complete the construction, you must provide a response via usingResponse() and then call resolve() to return the final GAStats instance.

    use BezhanSalleh\GoogleAnalytics\Support\GAStatsBuilder;
    
    $gaStats = GAStatsBuilder::make('Total Users', 'users')
        ->usingResponse($googleAnalyticsResponse)
        ->resolve();
  11. Use the GoogleAnalytics facade

    main

    The GoogleAnalytics facade provides a convenient proxy to the underlying FilamentGoogleAnalytics class. You can use it to access core functionality such as formatting numbers or retrieving analytics data via the for() method.

    use BezhanSalleh//GoogleAnalytics//Facades//GoogleAnalytics;
    
    // Example usage of available facade methods:
    $formatted = GoogleAnalytics::thousandsFormater();
    $analytics = GoogleAnalytics::for($propertyId);