PHP code example of bugfix666 / laravel-outbox

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/ */

    

bugfix666 / laravel-outbox example snippets


return [
    'table' => env('OUTBOX_TABLE', 'outbox_messages'),
    'connection' => env('OUTBOX_DB_CONNECTION', env('DB_CONNECTION')),

    // LogPublisher is for local development. Configure a real publisher in production.
    'publisher' => env('OUTBOX_PUBLISHER', \Bugfix666\LaravelOutbox\Publishers\LogPublisher::class),

    'worker' => [
        'batch_size' => 100,
        'lock_timeout' => 900,
        'lock_store' => 'database',
        'message_lock_timeout' => 300,
    ],

    'cleanup' => [
        'days' => 7,
    ],

    'retry' => [
        'max_attempts' => 5,
        'delay_seconds' => 60,
        'max_delay_seconds' => 3600,
        'multiplier' => 2,
    ],
];

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
bash
composer  vendor:publish --tag=outbox-config
php artisan vendor:publish --tag=outbox-migrations
php artisan migrate
bash
php artisan outbox:process
php artisan outbox:process --batch-size=200
bash
php artisan outbox:retry <message-uuid>
bash
php artisan outbox:cleanup --days=14