Laravel provides real-time broadcasting of events using channels and listeners. Here's how to use broadcasting in Laravel:
Step 1: Create an Event
Create an event that should be broadcasted. You can create an event by running the following command in your terminal:
php artisan make:event OrderShipped
This command will create a new event class OrderShipped
.
Step 2: Register Event in EventServiceProvider
Add the OrderShipped
event to the $listen
property in the EventServiceProvider
. This will allow the event to be broadcasted to the specified channel(s).
protected $listen = [
'App\Events\OrderShipped' => [
'App\Listeners\SendShipmentNotification',
],
];
Step 3: Create a Channel
Create a channel that will broadcast the event to the desired listeners. You can create a channel by running the following command:
php artisan make:channel OrderChannel
This command will create a new channel class OrderChannel
.
Step 4: Broadcasting Event
Broadcast the OrderShipped
event to the desired channel(s) using the broadcast
method.
use App\Events\OrderShipped;
broadcast(new OrderShipped($order))->toOthers();
This will broadcast the OrderShipped
event to all other connected clients on the specified channel.
Listening to Broadcasted Events
To listen to the broadcasted events, you need to create a listener that will receive the broadcasted event. Here's how to create a listener:
Step 1: Create a Listener
Create a listener that will handle the broadcasted event. You can create a listener by running the following command:
php artisan make:listener SendShipmentNotification
This command will create a new listener class SendShipmentNotification
.
Step 2: Implement the Handle Method
Implement the handle
method to define what should be done when the event is broadcasted.
public function handle(OrderShipped $event)
{
// Send shipment notification to the customer
}
Step 3: Register the Listener
Register the SendShipmentNotification
listener in the $listen
property in the EventServiceProvider
.
protected $listen = [
'App\Events\OrderShipped' => [
'App\Listeners\SendShipmentNotification',
],
];
Broadcasting with Socket.IO
Laravel provides Socket.IO broadcasting driver out of the box. To use this driver, you need to install the socket.io-client
and laravel-echo
packages.
npm install --save socket.io-client laravel-echo
After installing the packages, you need to create a new instance of the Echo
object and configure it with the broadcasting details in your resources/js/bootstrap.js
file.
import Echo from 'laravel-echo'
window.Echo = new Echo({
broadcaster: 'socket.io',
host: window.location.hostname + ':6001',
});
Now, you can use the Echo
object to listen to the broadcasted events.
window.Echo.channel('orders')
.listen('.order.shipped', function(data) {
console.log('Order shipped', data);
});
This will listen to the order.shipped
event on the orders
channel and log the data to the console when the event is received.