Event Broadcasting in Laravel allows server-side events to be broadcast to clients in real-time using channels. This is useful for building real-time features like notifications, chat systems, or live updates without requiring manual polling.
Laravel's Event Broadcasting was introduced to simplify building real-time web applications. By integrating seamlessly with WebSocket libraries like Pusher and Laravel Echo, it provides an easy-to-use API for event-based communication.
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.