Glossary

Event Broadcasting in Laravel

What is Event Broadcasting in Laravel?

Laravel's Event Broadcasting feature allows server-side events to be broadcast to clients in real-time via channels. This allows you to create real-time features like notifications, chat systems, and live updates without requiring manual polling.


Origin

Laravel Event Broadcasting was introduced to make it easier to create real-time web apps. It simplifies event-based communication by integrating with WebSocket frameworks like Pusher and Laravel Echo.


Why is Event Broadcasting Used?

  1. Real-Time Communication: Provides quick updates to connected clients.
  2. Reduces Client Polling: Removes the need for frequent client-server communication.
  3. Simplifies Integration: Works with Pusher and Redis right out of the box.

Best Practices.

  1. Secure Your Channels: For sensitive data, use private or presence channels that require authentication.
  2. Use Laravel Echo: Laravel Echo provides consistent client-side integration.
  3. Optimize Broadcast Drivers: Choose the right driver (Redis, Pusher, or custom WebSocket) based on your project's needs.

Example in Action

Create an event to broadcast:

php artisan make:event OrderShipped

In the event class, add the ShouldBroadcast interface:

namespace App\Events;

use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
use Illuminate\Foundation\Events\Dispatchable;

class OrderShipped implements ShouldBroadcast
{
    use Dispatchable, InteractsWithSockets;

    public $order;

    public function __construct($order)
    {
        $this->order = $order;
    }

    public function broadcastOn()
    {
        return ['orders'];
    }
}

Broadcast the event:

OrderShipped::dispatch($order);

Clients listening to the orders channel will receive real-time updates.

Start monitoring today

Websites go down and code throws errors. Ranetrace tells you when it happens to yours, why it matters and what to do next.

Start your 30-day free trial From $9 a month. No credit card required.