How to Build a Real-Time Chat App with Laravel Reverb


Creating a live chat system with Laravel Reverb involves integrating real-time communication features into your Laravel application. However, Laravel Reverb is primarily a webhook notification package and may not be suitable for real-time chat functionalities. Instead, we'll use Laravel Echo, Laravel Broadcasting, and a service like Pusher to implement real-time capabilities.

Here's a step-by-step guide to creating a live chat system in Laravel:

Step 1: Set Up Laravel

Make sure you have a Laravel application set up. If not, create a new Laravel project:

composer create-project --prefer-dist laravel/laravel live-chat-app
cd live-chat-app

Step 2: Install Laravel Echo and Pusher

Install the required packages:

composer require pusher/pusher-php-server npm install --save laravel-echo pusher-js

Step 3: Configure Pusher

Create an account on Pusher and get your credentials.

Update your .env file with your Pusher credentials:


BROADCAST_DRIVER=pusher PUSHER_APP_ID=your-pusher-app-id PUSHER_APP_KEY=your-pusher-app-key PUSHER_APP_SECRET=your-pusher-app-secret PUSHER_APP_CLUSTER=your-pusher-app-cluster

Update your config/broadcasting.php to include the Pusher configuration:

'pusher' => [ 'driver' => 'pusher', 'key' => env('PUSHER_APP_KEY'), 'secret' => env('PUSHER_APP_SECRET'), 'app_id' => env('PUSHER_APP_ID'), 'options' => [ 'cluster' => env('PUSHER_APP_CLUSTER'), 'useTLS' => true, ], ],

Step 4: Set Up Event and Listener

Create an event for the chat message:

php artisan make:event MessageSent

Update the generated event class (app/Events/MessageSent.php):

namespace App\Events; use Illuminate\Broadcasting\Channel; use Illuminate\Queue\SerializesModels; use Illuminate\Broadcasting\PrivateChannel; use Illuminate\Foundation\Events\Dispatchable; use Illuminate\Broadcasting\InteractsWithSockets; class MessageSent { use Dispatchable, InteractsWithSockets, SerializesModels; public $message; public $user; public function __construct($user, $message) { $this->user = $user; $this->message = $message; } public function broadcastOn() { return new PrivateChannel('chat'); } }

Step 5: Broadcast the Event

Enable broadcasting in the App\Providers\BroadcastServiceProvider by uncommenting the Broadcast::routes() line:

Broadcast::routes(); require base_path('routes/channels.php');

Add the authentication route in routes/channels.php:

Broadcast::channel('chat', function ($user) { return Auth::check(); });

Step 6: Create Chat Controller

Create a controller for handling chat messages:

php artisan make:controller ChatController

Update the controller (app/Http/Controllers/ChatController.php):

namespace App\Http\Controllers; use App\Events\MessageSent; use Illuminate\Http\Request; use Illuminate\Support\Facades\Auth; class ChatController extends Controller { public function sendMessage(Request $request) { $user = Auth::user(); $message = $request->input('message'); broadcast(new MessageSent($user, $message))->toOthers(); return response()->json(['status' => 'Message Sent!']); } }

Step 7: Set Up Frontend

Install Laravel Mix and dependencies:


npm install

Update resources/js/bootstrap.js to include Echo and Pusher:


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 });

Create a simple Vue.js component for the chat (you can use any frontend framework or vanilla JS):


// resources/js/components/ChatComponent.vue <template> <div> <div v-for="message in messages" :key="message.id"> <strong>{{ message.user.name }}</strong>: {{ message.text }} </div> <input v-model="newMessage" @keyup.enter="sendMessage"> </div> </template> <script> export default { data() { return { messages: [], newMessage: '' } }, mounted() { window.Echo.private('chat') .listen('MessageSent', (e) => { this.messages.push({ user: e.user, text: e.message }); }); }, methods: { sendMessage() { axios.post('/send-message', { message: this.newMessage }).then(response => { this.newMessage = ''; }); } } } </script>

Update resources/js/app.js to include the chat component:

import Vue from 'vue'; import ChatComponent from './components/ChatComponent.vue'; const app = new Vue({ el: '#app', components: { ChatComponent } });

Step 8: Update Routes

Add the route to handle sending messages in routes/web.php:

use App\Http\Controllers\ChatController; Route::post('/send-message', [ChatController::class, 'sendMessage'])->middleware('auth');

Step 9: Set Up Blade Template

Include the chat component in your Blade template (resources/views/welcome.blade.php or another template):

<!DOCTYPE html> <html> <head> <title>Live Chat</title> <meta name="csrf-token" content="{{ csrf_token() }}"> <script src="{{ mix('js/app.js') }}" defer></script> </head> <body> <div id="app"> <chat-component></chat-component> </div> </body> </html>

Step 10: Compile Assets

Compile your assets using Laravel Mix:

npm run dev

Conclusion

By following these steps, you've set up a live chat system in Laravel using Laravel Echo, Pusher, and Vue.js. This allows you to handle real-time communication efficiently, making your application more interactive and responsive. For more advanced features and customization, refer to the documentation of Laravel Echo and Pusher.

Post a Comment

0 Comments