If you need to store metadata on all events you can leverage Laravel's native models events when using the EloquentStoredEventRepository.
You must configure the package to use your own eloquent event storage model that extends the EloquentStoredEvent model. On that model you can hook into the model lifecycle hooks.
The StoredEvent instance will be passed on to any projector method that has a variable named $storedEvent. You'll also need the StoredEventRepository that is used by the application to update the stored event.
On the StoredEvent instance there is a property, meta_data, that returns an array. You can update this array to store any metadata you like.
Here's an example:
namespaceApp\Projectors;
useSpatie\EventSourcing\EventHandlers\Projectors\Projector;
useSpatie\EventSourcing\Models\StoredEvent;
useSpatie\EventSourcing\Facades\Projectionist;
useApp\Events\MoneyAdded;
classMetaDataProjectorextendsProjector
{
/*
* Here you can specify which event should trigger which method.
*/publicarray$handlesEvents = [
MoneyAdded::class => 'onMoneyAdded',
];
publicfunctiononMoneyAdded(StoredEvent $storedEvent, StoredEventRepository $repository)
{
if (! Projectionist::isReplaying()) {
$storedEvent->meta_data['user_id'] = auth()->user()->id;
$repository->update($storedEvent);
}
// ...
}
}