jooservices/laravel-events

EventSourcing and EventLog for Laravel with MongoDB storage

Maintainers

Package info

github.com/jooservices/laravel-events

pkg:composer/jooservices/laravel-events

Statistics

Installs: 9

Dependents: 0

Suggesters: 0

Stars: 0

Open Issues: 3

v1.1.0 2026-04-21 05:01 UTC

README

CI OpenSSF Scorecard PHP Version License: MIT Packagist Version

Lightweight Event Sourcing and Event Log persistence for Laravel with MongoDB storage. Store domain event payloads by aggregate and/or model change audit trails (prev/changed/diff) via Laravel's native event dispatcher.

Package name: jooservices/laravel-events

Introduction

This package adds two persistence features on top of Laravel's event system:

  1. Event Sourcing — Events implementing EventSourcingInterface are stored in a stored_events MongoDB collection (payload, aggregate id, metadata, user, time). Use for aggregate history, replay-oriented records, or audit by aggregate.
  2. Event Log — Events implementing LoggableModelInterface are stored in an event_logs collection with previous/changed state and a per-field diff. Use for audit trails and compliance.

You dispatch events as usual; package subscribers persist them to MongoDB. No custom bus or queue required.

Scope

Use this package when you need a reusable Laravel-standard base library for persisting event records or audit logs.

This package does not:

  • replace Laravel's event dispatcher
  • provide a projection/read-model framework
  • provide a business analytics or reporting layer
  • provide a full query/data-access toolkit
  • provide AI agents, AI data fetching, or an AI runtime

When to Use

Need Use
Persist domain events by aggregate for historical inspection or replay-aware workflows Event Sourcing
Persist model/entity changes with previous/current values and field diff Event Log
Need both domain history and field-level audit Use both, with separate focused events
Need dashboards, projections, analytics, or AI retrieval Build that in the application layer

Quick Start

Install

composer require jooservices/laravel-events

Publish config (optional)

php artisan vendor:publish --tag=laravel-events-config

Environment

MONGODB_URI=mongodb://127.0.0.1:27017
MONGODB_DATABASE=your_db
EVENTS_EVENTSOURCING_ENABLED=true
EVENTS_EVENT_LOG_ENABLED=true

Ensure a mongodb connection exists in config/database.php (see mongodb/laravel-mongodb).

Indexes

php artisan events:install-indexes

Basic Usage

Event Sourcing

Implement EventSourcingInterface and dispatch:

use JooServices\LaravelEvents\EventSourcing\Contracts\EventSourcingInterface;

class OrderCreated implements EventSourcingInterface
{
    public function __construct(public string $orderId, public array $items) {}

    public function payload(): array
    {
        return ['order_id' => $this->orderId, 'items' => $this->items];
    }

    public function aggregateId(): ?string
    {
        return $this->orderId;
    }
}

event(new OrderCreated('ORD-001', [['sku' => 'X', 'qty' => 2]]));

Events are stored in the stored_events collection. Optional: occurredAt(): ?\Carbon\CarbonInterface, metadata(): array. Use the HasEventSourcingDefaults trait to implement only payload() and aggregateId().

Recommended metadata keys include request_id, correlation_id, causation_id, source, channel, reason_code, schema_version, event_version, and optional tenant_id. The EventMetadata helper exposes constants and small factory methods for those conventions.

Event Log (Audit)

Implement LoggableModelInterface (and optionally HasLogAction) and dispatch with prev/changed state. Use the DefaultsToUpdatedAction trait when the action is always updated:

use JooServices\LaravelEvents\EventLog\Concerns\DefaultsToUpdatedAction;
use JooServices\LaravelEvents\EventLog\Contracts\LoggableModelInterface;
use JooServices\LaravelEvents\EventLog\Contracts\HasLogAction;

class OrderUpdated implements LoggableModelInterface, HasLogAction
{
    use DefaultsToUpdatedAction;

    public function __construct(public Order $model, public array $prev) {}

    public function getLoggableType(): string { return $this->model->getMorphClass(); }
    public function getLoggableId(): string { return (string) $this->model->getKey(); }
    public function getPrev(): array { return $this->prev; }
    public function getChanged(): array { return $this->model->getAttributes(); }
}

Changes are stored in event_logs with a computed diff. Query by entity_type + entity_id.

Recommended action names are available from JooServices\LaravelEvents\EventLog\EventLogAction: created, updated, deleted, restored, status_changed, corrected, synchronized, and imported.

Documentation

Full documentation is in the ./docs folder:

Document Description
docs/README.md Documentation index
Architecture Design, data flow, diagrams
Code structure Package layout and namespaces
Installation Requirements and setup
Configuration Config and context provider
Decision Guide Event Sourcing vs Event Log
Event Sourcing Stored events and aggregates
Event Log Audit trail and diff
Metadata Metadata keys, versioning, corrections
Operations Indexes, query patterns, retention, production safety
AI Integration Optional app-layer AI export examples
Development Composer commands, CI, release, and contributor workflow
Samples Complete code examples
API Reference EventService, interfaces, commands

Testing & Linting

composer test
composer test:coverage
composer lint       # Pint, PHPCS, PHPStan
composer lint:all   # lint + PHPMD
composer lint:fix
composer check      # lint:all + test

Git Hooks

Composer installs Git hooks automatically on dependency install and update:

composer install
composer update

The hooks are managed by CaptainHook and enforce:

  • commit-msg: Conventional Commits, for example fix: Correct event metadata merge
  • pre-commit: PHP syntax linting, staged secret scanning with gitleaks, Pint, PHPCS, PHPStan, and PHPMD
  • pre-push: gitleaks history scan when available, then composer test

If hooks need to be reinstalled manually:

vendor/bin/captainhook install --force --skip-existing

Install gitleaks locally to pass the pre-commit secret scan:

brew install gitleaks

AI Contributor Support

AI contributor guidance is intentionally documentation-only:

The package does not include AI runtime code, AI data fetching, authorization, redaction, or tool execution.

GitHub Actions

Configured workflows:

  • CI: Composer audit, Pint, PHPCS, PHPStan, PHPMD, PHPUnit coverage with a MongoDB service, and non-blocking dependency review for pull requests
  • Release: validate version tags, create GitHub releases, and trigger Packagist updates
  • PR Labeler: apply labels based on changed files
  • Semantic PR Title: enforce Conventional Commit-style PR titles
  • OpenSSF Scorecard: publish security posture results as SARIF

Coverage is archived as a workflow artifact. A Codecov badge is intentionally not shown because Codecov upload is not configured for this repository.

License

This project is licensed under the MIT License.