trypost/app/Observers/PostObserver.php
Paulo Castellano 2aef07dde6 Defer PostCreated with DB::afterCommit in the observer.
Keep after-commit local to created(), matching the saved() job hook, instead of marking the event itself.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-24 12:17:43 -03:00

39 lines
951 B
PHP

<?php
declare(strict_types=1);
namespace App\Observers;
use App\Enums\Automation\Trigger\Type as TriggerType;
use App\Enums\Post\Status as PostStatus;
use App\Events\PostCreated;
use App\Jobs\Automation\DispatchPostTriggerAutomationsJob;
use App\Models\Post;
use Illuminate\Support\Facades\DB;
class PostObserver
{
public function created(Post $post): void
{
DB::afterCommit(fn () => PostCreated::dispatch($post));
}
public function saved(Post $post): void
{
if (! $post->wasChanged('status')) {
return;
}
$triggerType = match ($post->status) {
PostStatus::Published => TriggerType::PostPublished,
PostStatus::Scheduled => TriggerType::PostScheduled,
default => null,
};
if ($triggerType === null) {
return;
}
DispatchPostTriggerAutomationsJob::dispatch($post, $triggerType)->afterCommit();
}
}