uniparticle / filament-engagement
Event analytics for Laravel and Filament 3: app event collection through a GraphQL mutation, reports, segments, targeted push campaigns and an AI assistant.
Package info
github.com/alielghazoly/filament-engagement
pkg:composer/uniparticle/filament-engagement
Requires
- php: ^8.1
- ext-json: *
- filament/filament: ^3.2
- illuminate/support: ^10.0
- nuwave/lighthouse: ^5.0
Requires (Dev)
None
Suggests
- anthropic-ai/sdk: ^1.14, needed for the Ask AI page when it uses Claude (not for Gemini)
Provides
None
Conflicts
None
Replaces
None
README
Event analytics for a Filament 3 panel: what users do in your apps (events the apps send), segments, targeted
pushes with results, audiences you can notify, and natural-language questions answered by Claude or Gemini.
Optionally it also logs every API and GraphQL call (the usage log, see usage.enabled).
Requires PostgreSQL, Lighthouse 5 and Laravel 10.
What it records
App events are always recorded: what your apps send with trackEvents (see App events).
The usage log is optional (ENGAGEMENT_TRACK_USAGE, usage.enabled; on by default in the package). Switched off,
no API or GraphQL call is recorded, content_opened is not recorded, and the pages API Calls and Call Log are
hidden. "Used the app" in segments then means "sent an event". Rows recorded earlier stay in the database.
The dashboard pages Usage Analytics (totals, click rate, events over time, top events and content, areas of the app, platforms and versions, most active users) and Activity Log (every event, with filters) are built on app events and are always shown.
With the usage log on: one row per GraphQL root field and per REST API call: operation name, type, signed-in user id or an anonymous visitor key, success, duration, platform and app version. Rows are written after the response is sent.
It does not store query bodies, variables, request payloads or raw IP addresses. The one exception is the
id of the item opened, for the operations listed under track (see App events). It records backend calls,
not screens: "most visited page" is inferred from the operations that load a page.
Introspection, unparsable documents and unknown field names are ignored. Requests rejected before GraphQL execution (for example by a custom validation rule) are not recorded.
Optional headers your apps can send: X-Platform, X-App-Version, X-Device-Id (a stable anonymous id,
better than IP + user agent for counting guests).
Requirements
- PHP 8.1+, Laravel 10, PostgreSQL (the reports use
jsonb,FILTERand window functions) - Filament 3 with an admin panel
- Lighthouse 5 (GraphQL): apps send events with a mutation. Your schema needs a
Mutationtype, or the package defines one. - A scheduler running
php artisan schedule:runevery minute (daily clean-up, segment refresh) - For Ask AI: a Gemini or Anthropic API key (
composer require anthropic-ai/sdkonly for Claude)
Install
composer require uniparticle/filament-engagement
php artisan migrate
php artisan vendor:publish --tag=engagement-config
php artisan lighthouse:clear-cache # if the schema is cached
Then:
-
Register the plugin in your Filament panel provider. Without
authorize()theviewEngagementgate decides, and access is denied if that gate is not defined.->plugins([ EngagementPlugin::make()->authorize(fn () => auth('dashboard')->user()?->hasRole('Super Admin')), ])
-
In
config/engagement.phpsetguards(orENGAGEMENT_GUARDS) to the guard your apps' tokens use, andusers.modelif it is notApp\Models\User. -
List the events your apps may send under
catalog, and check the other settings in the file. -
Optional, to use more of the package:
users.directory(names, units and communities in reports),business(your own reports),segments.rules(your own rules),push.channel(your push system) andaudiences. Each is a small class implementing a contract: see Extending.
Documentation
- Event collection: the
trackEventsmutation for your mobile apps - Reporting API: totals, time series, content and user reports for another dashboard
- Segments and campaigns: saved groups, targeted pushes, push results, push preferences
- Extending: connect your own users, reports, segment rules and push system
App events
The GraphQL mutation trackEvents, added to your Lighthouse schema by the package, collects what users do in your
apps: impressions, clicks, screen views and so on. These calls are not counted as application usage.
- Only names listed in
catalogare accepted; each says its section, action and allowed content types. - Events are validated one by one, stored in
engagement_app_events, and de-duplicated on the app'sevent_id. - The user comes from the token (
guards); a bad token gets an authentication error. - Without a token the events are stored as anonymous (
allow_guests). Guests are rate limited per device (X-Device-Id) and per IP address. trackaddscontent_openedwhen a GraphQL field that loads one item succeeds (only with the usage log).content_typescan rename a type (stored_as) or translate a per-user row id (client_id).- Events are kept forever unless
ENGAGEMENT_APP_EVENT_RETENTION_DAYSis set.
'catalog' => [ 'banner_click' => ['section' => 'banners', 'action' => 'click', 'content' => ['offer_banner'], 'required' => true], ],
Settings are under app_events.mutation. If the schema is cached, clear it after installing or upgrading
(php artisan lighthouse:clear-cache).
Reporting API
Read-only JSON reports over app events under api/analytics/v1/reports: summary, timeseries, breakdown,
content, content/{type}/{id}, options, and the user lists users and user-events.
php artisan engagement:api-key create "Marketing dashboard" # totals only php artisan engagement:api-key create "CRM" --users --days=90 # also user lists php artisan engagement:api-key list php artisan engagement:api-key revoke 1
Names, units and community filters come from your own class, set in users.directory, implementing
Contracts\UserDirectory. Reads of user lists are written to the log. Settings are under reports; set
reports.enabled to false to remove the routes.
Business reports
Figures from your own records (payments, requests ...) are served at reports/business/{name} with the same keys.
Register one class per report; each implements Contracts\BusinessReport:
'business' => [ 'payments' => PaymentsReport::class, ],
The package validates from, to, community, unit and the parameters the report declares; the class applies
them in build(). Return true from personal() for figures that identify people, to require users access.
Segments and push campaigns
Saved audiences (segments.rules, each implementing Contracts\SegmentRule), targeted pushes through your
notification system (push.channel, implementing Contracts\PushChannel) and push results. Two dashboard pages
(Segments, Push Campaigns) and endpoints under api/analytics/v1; API keys need --segments to change
segments and --send to send. Segments are refreshed daily by engagement:refresh-segments.
Wire your push code in two places:
use Uniparticle\FilamentEngagement\Push\{Campaigns, Deliveries}; // after the push service answers (never throws) Deliveries::record($notificationId, [['user_id' => 1, 'platform' => 'ios', 'accepted' => true]]); // optional: put the campaign ID in the payload $campaign = Campaigns::codeFor($notificationId);
App users read and set their preferences at api/analytics/v1/push-preferences with their login token.
Audiences
The Audiences page lists the users who engaged with one item (a banner, event, popup ...) and sends them a
notification through your application. It appears once audiences is configured.
Signals come from app events (by action, optionally by section) and from your own tables, for example read
receipts, which include history from before the package was installed.
// config/engagement.php 'track' => [ 'viewOfferBanner' => ['content_type' => 'offer_banner', 'argument' => 'id'], ], 'audiences' => [ 'popup' => [ 'label' => 'Popup', 'model' => Popup::class, 'title' => 'title_en', 'sources' => [ 'closed' => ['label' => 'Closed', 'table' => 'user_popups', 'item' => 'popup_id', 'at' => 'read_at'], 'clicked' => ['label' => 'Tapped', 'action' => 'click'], ], ], ], 'notifications' => [ 'sender' => SendAppNotification::class, // implements Contracts\NotificationSender 'max_recipients' => 10000, ],
where filters the item list, record_as names the stored content type when it differs from the audience (events
are stored as news), and a source with 'default' => false starts unticked.
Anonymous visitors are counted but cannot be notified. Audiences need the analytics tables on the same database
connection as your users.
Ask AI
-
Choose a provider and set the environment. For Google Gemini:
ENGAGEMENT_AI_PROVIDER=gemini ENGAGEMENT_AI_MODEL=gemini-3.1-flash-lite GEMINI_API_KEY= ENGAGEMENT_READER_USERNAME=engagement_reader ENGAGEMENT_READER_PASSWORD= # 12+ characters
For Claude:
ENGAGEMENT_AI_PROVIDER=anthropic ENGAGEMENT_AI_MODEL=claude-opus-5-5 ANTHROPIC_API_KEY= ENGAGEMENT_READER_USERNAME=engagement_reader ENGAGEMENT_READER_PASSWORD= # 12+ characters
-
Create the read-only database user (needs a database user allowed to create roles):
php artisan engagement:setup-reader
Run it again after upgrading, so the user gets the right tables.
On managed databases,
php artisan engagement:setup-reader --printprints the SQL for a DBA. -
If configuration is cached, run
php artisan config:cacheagain.
Models
| Setting | Meaning |
|---|---|
ENGAGEMENT_AI_PROVIDER |
anthropic or gemini. Left empty, a model name starting with gemini selects Gemini, anything else Claude |
ENGAGEMENT_AI_MODEL |
Any model of that provider that supports tool (function) calling. Left empty: claude-opus-5-5 or gemini-3.1-flash-lite |
ENGAGEMENT_AI_EFFORT |
How hard the model thinks: low, medium (default) or high; Gemini also minimal. Empty sends nothing, for models without this option |
Higher effort is slower and costs more. Smaller models write wrong queries more often, so try your real questions and
check the SQL shown under each answer. Other providers need their own Ai\Analyst subclass.
Safety
- The model's SQL runs as a user that can read only the two analytics tables. The package refuses to run if that user is a superuser or can read any other table.
- Each query is limited to one
SELECTwith allow-listed functions, inside a read-only transaction with a statement timeout and a row cap. - Questions and query results (including numeric user ids) are sent to the chosen provider (Anthropic or Google). User names are added in the dashboard afterwards and are never sent. On Google's free Gemini tier, Google may use what is sent to improve its products, so use a paid project for real data.
- Answers are rendered without links, images or raw HTML.
- Each question is billed by the provider. Questions are rate limited per admin and logged with the SQL used.
- A question can take longer than 60 seconds on a hard prompt; raise the web server's read timeout
(
fastcgi_read_timeoutin nginx) if you see gateway timeouts.
Maintenance
engagement:prune runs daily through the Laravel scheduler. It deletes the usage log older than
ENGAGEMENT_RETENTION_DAYS (180), and app events only if ENGAGEMENT_APP_EVENT_RETENTION_DAYS is set. Set ENGAGEMENT_ENABLED=false to stop tracking.
On busy applications the events table grows quickly: watch its size, and consider a separate database
(ENGAGEMENT_DB_CONNECTION, which turns the Audiences page off) or monthly partitioning.
License
MIT. See LICENSE.