Using Laravel Echo with Laravel WebSockets can help you build real-time chat applications efficiently. Laravel Echo is a JavaScript library that makes it easy to subscribe to channels and listen for events broadcast by Laravel. Laravel WebSockets, on the other hand, provides a WebSocket server for broadcasting events in real-time.
Here's a step-by-step guide on how to use Laravel Echo with Laravel WebSockets:
First, install the Laravel WebSockets package:
bashcomposer require beyondcode/laravel-websockets
Publish the configuration files to customize your WebSocket setup:
bashphp artisan vendor:publish --provider="BeyondCode\LaravelWebSockets\WebSocketsServiceProvider" --tag="migrations"
php artisan vendor:publish --provider="BeyondCode\LaravelWebSockets\WebSocketsServiceProvider" --tag="config"
Run the migrations:
bashphp artisan migrate
Configure your Laravel application to use the WebSocket driver for broadcasting. Update your .env
file:
envBROADCAST_DRIVER=pusher
Install Laravel Echo and the Pusher JavaScript library:
bashnpm install --save laravel-echo pusher-js
Configure Laravel Echo by updating your resources/js/bootstrap.js
file:
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,
});
Create an event that will be broadcasted to the WebSocket channel. For example, create a ChatMessageSent
event:
bashphp artisan make:event ChatMessageSent
In your controller or wherever you handle the chat message logic, broadcast the event:
phpbroadcast(new ChatMessageSent($message));
In your frontend JavaScript, use Laravel Echo to listen for events and update the UI accordingly:
javascriptEcho.channel('chat')
.listen('ChatMessageSent', (event) => {
console.log('Message sent:', event.message);
// Update the UI with the new message
});