<?php
namespace App\Jobs;
use App\Models\OutboxMessage; use Illuminate\Bus\Queueable; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Foundation\Bus\Dispatchable; use Illuminate\Queue\InteractsWithQueue; use Illuminate\Queue\SerializesModels; use Illuminate\Support\Facades\DB;
final class PublishOutboxMessagesJob implements ShouldQueue { use Dispatchable,InteractsWithQueue,Queueable,SerializesModels; public function handle(): void { OutboxMessage::query()->whereNull('published_at')->where('available_at','<=',now())->orderBy('id')->limit(100)->get()->each(function(OutboxMessage $m){ DB::transaction(function()use($m){$locked=OutboxMessage::whereKey($m->id)->lockForUpdate()->first(); if(!$locked||$locked->published_at)return; ProcessOutboxMessageJob::dispatch($locked->id)->onQueue($locked->queue)->afterCommit(); $locked->update(['published_at'=>now(),'attempts'=>$locked->attempts+1]);}); }); } }
