Back to Engineering Notes
Laravel ConceptsEngineering Note

10. Broadcasting & Events

I use Events and Broadcasting to build systems that are decoupled, scalable, and capable of real-time communication.

🧠 Broadcasting & Events (Event-Driven Design)

I use Events and Broadcasting to build systems that are decoupled, scalable, and capable of real-time communication.


🎯 Core Idea

Instead of writing tightly coupled logic like:

plain text
create user → send email → write log → notify UI

👉 I trigger one event:

plain text
UserRegistered

👉 and let multiple parts of the system react independently


🔄 How It Works (Flow)

1. an action happens (e.g., user registers)

1. system emits an event

1. multiple listeners handle different tasks

Example:

Listener A → send email
Listener B → write audit log
Listener C → push notification

👉 one trigger, multiple independent actions


🧩 Laravel Example

Create Event

plain text
php artisanmake:event UserRegistered
plain text
class UserRegistered
{
    public function __construct(public $user) {}
}

Create Listener

plain text
php artisanmake:listener SendWelcomeEmail
plain text
class SendWelcomeEmail
{
    public function handle(UserRegistered $event)
    {
        Mail::to($event->user->email)->send(new WelcomeMail());
    }
}

Dispatch Event

plain text
event(new UserRegistered($user));

🧩 Broadcasting Example

To send event to frontend in real-time:

plain text
class MessageSent implements ShouldBroadcast
{
    public function broadcastOn()
    {
        return ['chat-channel'];
    }
}

👉 event will be broadcast to clients


🧩 Key Concepts

Events

represent something that already happened
should be named clearly (business-level meaning)

Listeners

handle reactions
each has one responsibility

Broadcasting

sends events to frontend in real time

🧠 Why I Use This

decouples system components
makes code easier to extend
allows adding features without modifying core logic
supports async processing (can combine with queues)

⚖️ Tradeoff Awareness

harder to trace flow (not linear)
debugging requires good logging
can become complex if overused

🔗 Events + Queues (Important)

👉 event triggers → listener runs in background

faster response
non-blocking
scalable

📌 Practical Rule

> use events to decouple logic, not to hide it


💬 Summary

I use:

Events → represent system actions
Listeners → handle responsibilities
Broadcasting → deliver real-time updates

👉 to build systems that are modular, scalable, and flexible 👍