In today's world, real-time communication has become essential. Chat applications are a crucial part of this formula, and Laravel is one of the most popular frameworks for developing modern web applications. In this article, we will guide you step by step on how to create a real-time chat system using Laravel and Pusher, a messaging platform that facilitates the implementation of real-time functionalities.
Before you start, make sure you have the following:
First, you will need to create a new project in Laravel. Open your terminal and run the following command:
composer create-project --prefer-dist laravel/laravel laravel-chat
Navigate to your project directory:
cd laravel-chat
Copy the .env.example file and rename it to .env. Then, edit this file to set your database credentials and other necessary parameters.
To use the broadcasting technology in Laravel, you need to generate an application key:
php artisan key:generate
You need to install the Pusher library for PHP. From your project's terminal, run:
composer require pusher/pusher-php-server
Add the Pusher configurations to your .env file:
BROADCAST_DRIVER=pusher PUSHER_APP_ID=your_app_id PUSHER_APP_KEY=your_app_key PUSHER_APP_SECRET=your_app_secret PUSHER_APP_CLUSTER=your_app_cluster
Make sure the Pusher configuration is correctly set up in the config/broadcasting.php file:
'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, ], ],
Generate a model and a migration:
php artisan make:model Message -m
Edit the migration created in database/migrations to define the structure of the messages table:
public function up() { Schema::create('messages', function (Blueprint $table) { $table->id(); $table->string('user'); $table->text('message'); $table->timestamps(); }); }
Don’t forget to run the migration:
php artisan migrate
Now, create a controller to handle chat actions:
php artisan make:controller ChatController
In ChatController.php, add the following method:
use App\Models\Message; use Pusher\Pusher; public function sendMessage(Request $request) { $message = new Message(); $message->user = $request->user; $message->message = $request->message; $message->save(); $options = [ 'cluster' => env('PUSHER_APP_CLUSTER'), 'useTLS' => true, ]; $pusher = new Pusher( env('PUSHER_APP_KEY'), env('PUSHER_APP_SECRET'), env('PUSHER_APP_ID'), $options ); $pusher->trigger('chat', 'message', [ 'user' => $message->user, 'message' => $message->message, ]); return response()->json(['status' => 'Message sent']); }
Open the routes/web.php file and add a new route for your controller:
Route::post('/send-message', [ChatController::class, 'sendMessage']);
Create a new view called chat.blade.php in the resources/views folder and add the following HTML and JavaScript code:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Real-Time Chat</title> <script src="https://js.pusher.com/7.0/pusher.min.js"></script> </head> <body> <div id="chat-box"></div> <input type="text" id="user" placeholder="Your name"> <input type="text" id="message" placeholder="Your message"> <button id="send">Send</button> <script> const pusher = new Pusher('your_app_key', { cluster: 'your_app_cluster' }); const channel = pusher.subscribe('chat'); channel.bind('message', function(data) { const chatBox = document.getElementById('chat-box'); chatBox.innerHTML += `<p><strong>${data.user}</strong>: ${data.message}</p>`; }); document.getElementById('send').onclick = function() { const user = document.getElementById('user').value; const message = document.getElementById('message').value; fetch('/send-message', { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-CSRF-TOKEN': '{{ csrf_token() }}' }, body: JSON.stringify({ user, message }) }); } </script> </body> </html>
Finally, run your Laravel server:
php artisan serve
Access http://localhost:8000/chat in your browser and test the chat system.
We have covered all the necessary steps to create a real-time chat system using Laravel and Pusher. Now you can customize and expand this functionality according to your needs. From adding authentication systems to improving the frontend design, the possibilities are endless. Good luck developing your chat application!
Page loaded in 35.37 ms