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



Image not found!!

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:

Prerequisites:

  1. Install Laravel Echo and Pusher:

    bash
    npm install --save laravel-echo pusher-js
  2. Install Laravel WebSockets:

    bash
    composer require beyondcode/laravel-websockets
  3. Publish the WebSockets Configuration:

    bash
    php artisan vendor:publish --provider="BeyondCode\LaravelWebSockets\WebSocketsServiceProvider" --tag="config"
  4. Configure Broadcasting in Laravel: Update your .env file with the necessary broadcasting configurations. Set the BROADCAST_DRIVER to pusher and configure your Pusher credentials.

Setting Up Laravel Echo:

  1. Configure Laravel Echo: In your resources/js/bootstrap.js file, configure Laravel Echo with your Pusher credentials:

    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, });
  2. 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:

    javascript
    window.Echo.channel('chat') .listen('ChatEvent', (event) => { console.log('New message:', event.message); // Handle the incoming message });

Using Laravel WebSockets:

  1. Define Events: Create an event class for your chat messages. For example, run the following command to generate an event:

    bash
    php artisan make:event ChatEvent

    Update the event class to handle the broadcast data:

    php
    public function broadcastOn() { return new Channel('chat'); } public function broadcastWith() { return ['message' => $this->message]; }
  2. Broadcast Events: In your application logic, broadcast the event when a new message is created:

    php
    broadcast(new ChatEvent($message));
  3. Run the WebSocket Server: Start the Laravel WebSocket server:

    bash
    php artisan websockets:serve

    This will start a WebSocket server on the specified host and port.