1. Go to this page and download the library: Download bugfix666/laravel-outbox library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
use Bugfix666\LaravelOutbox\Services\OutboxService;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
final readonly class CreatePayment
{
public function __construct(private OutboxService $outboxService)
{
}
public function handle(PaymentData $data): Payment
{
$connectionName = config('outbox.connection') ?: config('database.default');
return DB::connection($connectionName)->transaction(function () use ($data, $connectionName): Payment {
// The business model must use the same connection as the outbox.
$payment = Payment::on($connectionName)->create([
'id' => (string) Str::uuid(),
'amount' => $data->amount,
'currency' => $data->currency,
'status' => 'pending',
]);
$this->outboxService->store(
aggregateType: 'Payment',
aggregateId: (string) $payment->getKey(),
eventType: 'payment.requested',
payload: [
'event_id' => (string) Str::uuid(),
'payment_id' => (string) $payment->getKey(),
'amount' => $payment->amount,
'currency' => $payment->currency,
],
);
return $payment;
});
}
}
use Illuminate\Support\Facades\Schedule;
Schedule::command('outbox:process --batch-size=100')
->everyMinute()
->withoutOverlapping();
use Bugfix666\LaravelOutbox\Events\OutboxEvent;
final class HandlePaymentRequested
{
public function handle(OutboxEvent $event): void
{
if ($event->eventType !== 'payment.requested') {
return;
}
// Handle the event. Make this handler idempotent.
}
}
use Bugfix666\LaravelOutbox\Contracts\OutboxPublisher;
use Bugfix666\LaravelOutbox\Publishers\QueuePublisher;
$this->app->bind(OutboxPublisher::class, fn () => new QueuePublisher('outbox-events'));
namespace App\Outbox;
use Bugfix666\LaravelOutbox\Contracts\OutboxPublisher;
use RuntimeException;
final class RabbitMqPublisher implements OutboxPublisher
{
public function __construct(private BrokerClient $client)
{
}
public function publish(string $eventType, array $payload, ?string $aggregateId = null): bool
{
// Publish to the broker and wait for its publisher confirmation.
// Throw if the broker did not accept the message durably.
$accepted = $this->client->publish($eventType, $payload, $aggregateId);
if (!$accepted) {
throw new RuntimeException('The broker did not confirm publication.');
}
return true;
}
}
use Bugfix666\LaravelOutbox\Enums\OutboxStatus;
use Bugfix666\LaravelOutbox\Models\OutboxMessage;
$failed = OutboxMessage::query()
->whereNotNull('failed_at')
->get();
$status = $failed->first()?->getStatus(); // OutboxStatus::FAILED