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.
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.
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.