Get expert guidance in a few days with a Laravel code review

Laravel Event Projector Released

Published on by

Laravel Event Projector Released image

Freek Van der Herten and the Spatie crew have been working on Laravel Event Projector, a package for event sourcing in Laravel. The first stable version (v1.0.0) is now live!

You can install Event Projector in your project with composer, and thanks to Laravel’s package auto-discovery, you’re ready to go after you publish the package’s migrations and configuration!

composer require spatie/laravel-event-projector:^1.0.0

Event Project requires PHP 7.2, so your app will need to support the latest version of PHP, versus the Laravel constraint of PHP >=7.1.3.

What is Event Sourcing

According to Event Sourcing Pattern, an overview of event sourcing is as follows:

Instead of storing just the current state of the data in a domain, use an append-only store to record the full series of actions taken on that data. The store acts as the system of record and can be used to materialize the domain objects. This can simplify tasks in complex domains, by avoiding the need to synchronize the data model and the business domain, while improving performance, scalability, and responsiveness. It can also provide consistency for transactional data, and maintain full audit trails and history that can enable compensating actions.

I’d recommend reading the whole article, it provides an excellent overview and some ideas on when using this pattern is appropriate, and other situations where this pattern might not be useful.

I like Spatie’s explanation of Event Sourcing from the documentation’s introduction:

Event sourcing is to data what Git is to code. Most applications only have their current state stored in a database. A lot of useful information gets lost: you don’t know how the application got to this state.

Event sourcing tries to solve this problem by storing all events that happen in your app. The state of your application is built by listening to those events.

Here’s a traditional example to make it more clear. Imagine you’re a bank. Your clients have accounts. Storing the balance of the accounts wouldn’t be enough, all the transactions should be remembered too. With event sourcing, the balance isn’t a standalone database field, but a value calculated from the stored transactions. This is only one of the many benefits event sourcing brings to the table.

This package aims to be the simple and very pragmatic way to get started with event sourcing in Laravel.

It seems like Event Projector helps to make event sourcing simple and the documentation has helped me solidify how to use event sourcing using concepts in Laravel I am already familiar with.

Basic Event Sourcing in Laravel

To get familiar with event sourcing using the Event Projector package, you should check out Writing your first projector to get an idea of the pieces involved.

At a high level, (forgive me if I am not perfect in my assessment, event sourcing is a new concept for me) event sourcing with Event Projector involves:

  • Eloquent models
  • Events implementing the ShouldBeStored interface
  • Projector classes

From the documentation, here’s an example of a model class with the createWithAttributes static method:

namespace App;
 
use App\Events\AccountCreated;
use App\Events\AccountDeleted;
use App\Events\MoneyAdded;
use App\Events\MoneySubtracted;
use Illuminate\Database\Eloquent\Model;
use Ramsey\Uuid\Uuid;
 
class Account extends Model
{
protected $guarded = [];
 
protected $casts = [
'broke_mail_send' => 'bool',
];
 
public static function createWithAttributes(array $attributes): Account
{
/*
* Let's generate a uuid.
*/
$attributes['uuid'] = (string) Uuid::uuid4();
 
/*
* The account will be created inside this event using the generated uuid.
*/
event(new AccountCreated($attributes));
 
/*
* The uuid will be used the retrieve the created account.
*/
return static::uuid($attributes['uuid']);
}
 
public function addMoney(int $amount)
{
event(new MoneyAdded($this->uuid, $amount));
}
 
public function subtractMoney(int $amount)
{
event(new MoneySubtracted($this->uuid, $amount));
}
 
public function delete()
{
event(new AccountDeleted($this->uuid));
}
 
/*
* A helper method to quickly retrieve an account by uuid.
*/
public static function uuid(string $uuid): ?Account
{
return static::where('uuid', $uuid)->first();
}
}

The thing to note here is the events being fired for AccountCreated, MoneyAdded, MoneySubtracted, and AccountDeleted.

Here’s an example of the MoneyAdded event. The ShouldBeStored interface that signifies to the Event Projector package that this event should be stored:

namespace App\Events;
 
use Spatie\EventProjector\ShouldBeStored;
 
class MoneyAdded implements ShouldBeStored
{
/** @var string */
public $accountUuid;
 
/** @var int */
public $amount;
 
public function __construct(string $accountUuid, int $amount)
{
$this->accountUuid = $accountUuid;
 
$this->amount = $amount;
}
}

Finally, here’s a partial example of an event handler inside of a projector class to add money to the account balance (that’s my favorite type of bank event):

public function onMoneyAdded(MoneyAdded $event)
{
$account = Account::uuid($event->accountUuid);
 
$account->balance += $event->amount;
 
$account->save();
}

To tie it all together, here’s an example from the documentation of creating a new account and adding money:

Account::createWithAttributes(['name' => 'Luke']);
Account::createWithAttributes(['name' => 'Leia']);
 
$account = Account::where(['name' => 'Luke'])->first();
$anotherAccount = Account::where(['name' => 'Leia'])->first();
 
$account->addMoney(1000);
$anotherAccount->addMoney(500);
$account->subtractMoney(50);

I imagine that Luke and Leia’s balances represent the Galactic Credit Standard, although, I am not entirely sure if they would be on the grid like this.

One section of this documentation stuck out to me as a benefit of using event sourcing via this package:

The cool thing about projectors is that you can write them after events have happened. Imagine that someone at the bank wants to have a report of the average balance of each account. You would be able to write a new projector, replay all events, and have that data.

The idea that you can write new projectors after events have happened seems powerful. It means that you don’t have to “get it all right” up front, and can iterate.

If you’re concerned about performance, the documentation claims that projects are “very fast to query.”

Learn More

I’d encourage you to read through the Event Projector Documentation to get started and make sure you have a fresh copy of PHP 7.2 available. Spatie also has a Demo Laravel Event Projector Application showcasing the Event Projector package that you probably want to check out.

You can download the code, star the repo, and contribute to Event Projector on the GitHub repo. At the time of writing, Event Projector is already up to 15 contributors leading up to the stable 1.0 release. Nice work Spatie! Event Projector looks like another excellent package for the Laravel community.

Paul Redmond photo

Staff writer at Laravel News. Full stack web developer and author.

Filed in:
Cube

Laravel Newsletter

Join 40k+ other developers and never miss out on new tips, tutorials, and more.

image
Curotec

Curotec helps software teams hire the best Laravel developers in Latin America. Click for rates and to learn more about how it works.

Visit Curotec
Curotec logo

Curotec

World class Laravel experts with GenAI dev skills. LATAM-based, embedded engineers that ship fast, communicate clearly, and elevate your product. No bloat, no BS.

Curotec
Bacancy logo

Bacancy

Supercharge your project with a seasoned Laravel developer with 4-6 years of experience for just $3200/month. Get 160 hours of dedicated expertise & a risk-free 15-day trial. Schedule a call now!

Bacancy
Tinkerwell logo

Tinkerwell

The must-have code runner for Laravel developers. Tinker with AI, autocompletion and instant feedback on local and production environments.

Tinkerwell
Cut PHP Code Review Time & Bugs into Half with CodeRabbit logo

Cut PHP Code Review Time & Bugs into Half with CodeRabbit

CodeRabbit is an AI-powered code review tool that specializes in PHP and Laravel, running PHPStan and offering automated PR analysis, security checks, and custom review features while remaining free for open-source projects.

Cut PHP Code Review Time & Bugs into Half with CodeRabbit
Get expert guidance in a few days with a Laravel code review logo

Get expert guidance in a few days with a Laravel code review

Expert code review! Get clear, practical feedback from two Laravel devs with 10+ years of experience helping teams build better apps.

Get expert guidance in a few days with a Laravel code review
Kirschbaum logo

Kirschbaum

Providing innovation and stability to ensure your web application succeeds.

Kirschbaum
Shift logo

Shift

Running an old Laravel version? Instant, automated Laravel upgrades and code modernization to keep your applications fresh.

Shift
Harpoon: Next generation time tracking and invoicing logo

Harpoon: Next generation time tracking and invoicing

The next generation time-tracking and billing software that helps your agency plan and forecast a profitable future.

Harpoon: Next generation time tracking and invoicing
Lucky Media logo

Lucky Media

Get Lucky Now - the ideal choice for Laravel Development, with over a decade of experience!

Lucky Media
Lunar: Laravel E-Commerce logo

Lunar: Laravel E-Commerce

E-Commerce for Laravel. An open-source package that brings the power of modern headless e-commerce functionality to Laravel.

Lunar: Laravel E-Commerce
SaaSykit: Laravel SaaS Starter Kit logo

SaaSykit: Laravel SaaS Starter Kit

SaaSykit is a Multi-tenant Laravel SaaS Starter Kit that comes with all features required to run a modern SaaS. Payments, Beautiful Checkout, Admin Panel, User dashboard, Auth, Ready Components, Stats, Blog, Docs and more.

SaaSykit: Laravel SaaS Starter Kit

The latest

View all →
A new beta of Laravel Wayfinder just dropped image

A new beta of Laravel Wayfinder just dropped

Read article
Ben Bjurstrom: Laravel is the best Vibecoding stack for 2026 image

Ben Bjurstrom: Laravel is the best Vibecoding stack for 2026

Read article
Laravel Altitude - Opinionated Claude Code agents and commands for TALL stack development image

Laravel Altitude - Opinionated Claude Code agents and commands for TALL stack development

Read article
JSON:API Resource in Laravel 12.45 image

JSON:API Resource in Laravel 12.45

Read article
Caching With MongoDB for Faster Laravel Apps image

Caching With MongoDB for Faster Laravel Apps

Read article
Laravel 12.44 Adds HTTP Client afterResponse() Callbacks image

Laravel 12.44 Adds HTTP Client afterResponse() Callbacks

Read article