Skip to content

Commit

Permalink
Merge pull request #384 from aidan-casey/fix-event-order-bug
Browse files Browse the repository at this point in the history
Fixes bug with retrieving last event
  • Loading branch information
freekmurze authored Jan 3, 2023
2 parents f7266e5 + 58fbca2 commit b6e65b3
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,7 @@ public function lastEvent(string ...$eventClasses): ?EloquentStoredEvent
fn (self $query) => $query->whereEvent(...$eventClasses)
)
->orderByDesc('created_at')
->orderByDesc('id')
->first();
}
}
15 changes: 15 additions & 0 deletions tests/Models/EloquentStoredEventQueryBuilderTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

namespace Spatie\EventSourcing\Tests\Models;

use Carbon\Carbon;
use Illuminate\Support\InteractsWithTime;

use function PHPUnit\Framework\assertEquals;
Expand Down Expand Up @@ -104,3 +105,17 @@
assertInstanceOf(EventWithCarbon::class, $storedEvent);
assertEquals($date, $storedEvent->value);
});

it('retrieves last event of type when two were created at the same time', function () {
Carbon::setTestNow();

event(new MoneyAdded(50));
event(new MoneyAdded(10));

$event = EloquentStoredEvent::query()->lastEvent(MoneyAdded::class);
/** @var MoneyAdded $storedEvent */
$storedEvent = $event->toStoredEvent()->event;

assertInstanceOf(MoneyAdded::class, $storedEvent);
assertEquals(10, $storedEvent->amount);
});

0 comments on commit b6e65b3

Please sign in to comment.