advanced
Step 14 of 15
Events and Listeners
Laravel Framework
Events and Listeners
Events provide a way to decouple different parts of your application by implementing the observer pattern. When something significant happens (a user registers, an order is placed, a post is published), you fire an event. Listeners respond to that event and perform actions like sending emails, logging activity, updating caches, or notifying external services. This separation of concerns makes your code more modular, testable, and easier to maintain because each listener handles a single responsibility independently.
Creating Events and Listeners
<?php
// php artisan make:event OrderPlaced
// php artisan make:listener SendOrderConfirmation --event=OrderPlaced
// app/Events/OrderPlaced.php
class OrderPlaced
{
use Dispatchable, InteractsWithSockets, SerializesModels;
public function __construct(
public readonly Order $order
) {}
}
// app/Listeners/SendOrderConfirmation.php
class SendOrderConfirmation
{
public function handle(OrderPlaced $event): void
{
$order = $event->order;
Mail::to($order->user->email)->send(new OrderConfirmationMail($order));
}
}
// app/Listeners/UpdateInventory.php
class UpdateInventory
{
public function handle(OrderPlaced $event): void
{
foreach ($event->order->items as $item) {
$item->product->decrement('stock', $item->quantity);
}
}
}
// Register in EventServiceProvider
protected $listen = [
OrderPlaced::class => [
SendOrderConfirmation::class,
UpdateInventory::class,
LogOrderActivity::class,
],
];
// Fire the event from anywhere
OrderPlaced::dispatch($order);
// or: event(new OrderPlaced($order));
Notifications
<?php
// php artisan make:notification OrderShipped
class OrderShipped extends Notification
{
public function via($notifiable): array
{
return ['mail', 'database'];
}
public function toMail($notifiable): MailMessage
{
return (new MailMessage)
->subject('Your order has shipped!')
->line('Your order #' . $this->order->id . ' is on its way.')
->action('Track Order', url('/orders/' . $this->order->id));
}
}
// Send notification
$user->notify(new OrderShipped($order));
Pro tip: Use queued listeners (implements ShouldQueue) for slow operations like sending emails, so the user does not have to wait. Events are perfect for extending functionality without modifying existing code — just add a new listener without touching the code that fires the event.
Key Takeaways
- Events decouple your code by separating "something happened" from "what to do about it."
- Multiple listeners can respond to a single event, each handling one responsibility.
- Use queued listeners for slow operations like emails, API calls, and file processing.
- Notifications send alerts via multiple channels (email, database, SMS, Slack) from a single class.
- Events make your application extensible — add new behavior by adding listeners, not modifying existing code.