Using Laravel Echo with Laravel WebSockets to build a real-time chat application is a powerful combination. Laravel Echo is a JavaScript library that makes it easy to work with WebSockets and other broadcast technologies, and Laravel WebSockets is a package that enables real-time communication in Laravel applications. Here's a step-by-step guide on how to use them together:
Install Laravel Echo and Pusher:
bashnpm install --save laravel-echo pusher-js
Install Laravel WebSockets:
bashcomposer require beyondcode/laravel-websockets
Publish the WebSockets Configuration:
bashphp artisan vendor:publish --provider="BeyondCode\LaravelWebSockets\WebSocketsServiceProvider" --tag="config"
Configure Broadcasting in Laravel:
Update your .env
file with the necessary broadcasting configurations. Set the BROADCAST_DRIVER
to pusher
and configure your Pusher credentials.
Configure Laravel Echo:
In your resources/js/bootstrap.js
file, configure Laravel Echo with your Pusher credentials:
javascriptimport Echo from 'laravel-echo';
window.Pusher = require('pusher-js');
window.Echo = new Echo({
broadcaster: 'pusher',
key: process.env.MIX_PUSHER_APP_KEY,
cluster: process.env.MIX_PUSHER_APP_CLUSTER,
encrypted: true,
});
Subscribe to a Channel: In your Vue component or JavaScript file, you can subscribe to a channel to listen for events. For example, to subscribe to a chat channel:
javascriptwindow.Echo.channel('chat')
.listen('ChatEvent', (event) => {
console.log('New message:', event.message);
// Handle the incoming message
});
Define Events: Create an event class for your chat messages. For example, run the following command to generate an event:
bashphp artisan make:event ChatEvent
Update the event class to handle the broadcast data:
phppublic function broadcastOn()
{
return new Channel('chat');
}
public function broadcastWith()
{
return ['message' => $this->message];
}
Broadcast Events: In your application logic, broadcast the event when a new message is created:
phpbroadcast(new ChatEvent($message));
Run the WebSocket Server: Start the Laravel WebSocket server:
bashphp artisan websockets:serve
This will start a WebSocket server on the specified host and port.