Sistema de Eventos

O sistema de eventos do Laravel permite desacoplar componentes da aplicação, facilitando manutenção e testes.

Criando um Evento

// app/Events/PostCreated.php
namespace App\Events;

use App\Models\Post;
use Illuminate\Foundation\Events\Dispatchable;

class PostCreated
{
    use Dispatchable;
    
    public function __construct(
        public Post $post
    ) {}
}

Criando um Listener

// app/Listeners/SendPostNotification.php
namespace App\Listeners;

use App\Events\PostCreated;
use Illuminate\Support\Facades\Mail;

class SendPostNotification
{
    public function handle(PostCreated $event): void
    {
        Mail::to($event->post->author->email)
            ->send(new PostCreatedNotification($event->post));
    }
}

Disparando Eventos

// No Controller
PostCreated::dispatch($post);

// Ou no Model
protected $dispatchesEvents = [
    'created' => PostCreated::class,
];