How to use Laravel Echo with Laravel WebSockets for building real-time chat applications



Image not found!!

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:

1. Install Laravel WebSockets

First, install the Laravel WebSockets package:

bash
composer require beyondcode/laravel-websockets

2. Publish Configuration

Publish the configuration files to customize your WebSocket setup:

bash
php artisan vendor:publish --provider="BeyondCode\LaravelWebSockets\WebSocketsServiceProvider" --tag="migrations" php artisan vendor:publish --provider="BeyondCode\LaravelWebSockets\WebSocketsServiceProvider" --tag="config"

Run the migrations:

bash
php artisan migrate

3. Configure Broadcasting

Configure your Laravel application to use the WebSocket driver for broadcasting. Update your .env file:

env
BROADCAST_DRIVER=pusher

4. Install Laravel Echo and Pusher

Install Laravel Echo and the Pusher JavaScript library:

bash
npm install --save laravel-echo pusher-js

5. Configure Laravel Echo

Configure Laravel Echo by updating your resources/js/bootstrap.js file:

javascript
import 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, });

6. Create WebSocket Event

Create an event that will be broadcasted to the WebSocket channel. For example, create a ChatMessageSent event:

bash
php artisan make:event ChatMessageSent

7. Broadcast Event

In your controller or wherever you handle the chat message logic, broadcast the event:

php
broadcast(new ChatMessageSent($message));

8. Listen for Events

In your frontend JavaScript, use Laravel Echo to listen for events and update the UI accordingly:

javascript
Echo.channel('chat') .listen('ChatMessageSent', (event) => { console.log('Message sent:', event.message); // Update the UI with the new message });