{"id":4074,"date":"2023-11-04T23:14:03","date_gmt":"2023-11-04T23:14:03","guid":{"rendered":"http:\/\/localhost:10003\/how-to-build-a-chat-application-with-laravel-echo-and-pusher\/"},"modified":"2023-11-05T05:48:00","modified_gmt":"2023-11-05T05:48:00","slug":"how-to-build-a-chat-application-with-laravel-echo-and-pusher","status":"publish","type":"post","link":"http:\/\/localhost:10003\/how-to-build-a-chat-application-with-laravel-echo-and-pusher\/","title":{"rendered":"How to Build a Chat Application with Laravel Echo and Pusher"},"content":{"rendered":"
In this tutorial, we will learn how to build a real-time chat application using Laravel Echo and Pusher. Laravel Echo is a JavaScript library that makes it easy to handle real-time events in Laravel applications. Pusher is a hosted service that allows us to send and receive real-time messages.<\/p>\n
By the end of this tutorial, you will have a fully functional chat application where users can send and receive messages in real-time.<\/p>\n
To follow along with this tutorial, you will need the following:<\/p>\n
First, let’s setup a new Laravel project by running the following command in your terminal:<\/p>\n
composer create-project --prefer-dist laravel\/laravel chatapp\n<\/code><\/pre>\nThis will create a new Laravel project named chatapp<\/code>. Once the project is created, navigate to the project directory:<\/p>\ncd chatapp\n<\/code><\/pre>\nStep 2: Install Laravel Echo<\/h3>\n
To install Laravel Echo, we need to install the laravel-echo<\/code> package via npm:<\/p>\nnpm install --save laravel-echo pusher-js\n<\/code><\/pre>\nThis will install the required packages for Laravel Echo and Pusher. Next, we need to configure Laravel Echo to work with our application.<\/p>\n
Step 3: Configure Laravel Echo<\/h3>\n
Open the bootstrap.js<\/code> file located in the resources\/js<\/code> directory and add the following lines of code at the top of the file:<\/p>\nimport Echo from 'laravel-echo';\n\nwindow.Pusher = require('pusher-js');\n\nwindow.Echo = new Echo({\n broadcaster: 'pusher',\n key: process.env.MIX_PUSHER_APP_KEY,\n cluster: process.env.MIX_PUSHER_APP_CLUSTER,\n encrypted: true\n});\n<\/code><\/pre>\nThis will configure Laravel Echo with the required settings. Next, open the .env<\/code> file located in the root directory of your Laravel project and add the following lines of code:<\/p>\nPUSHER_APP_ID=your_app_id\nPUSHER_APP_KEY=your_app_key\nPUSHER_APP_SECRET=your_app_secret\nPUSHER_APP_CLUSTER=your_app_cluster\n<\/code><\/pre>\nReplace your_app_id<\/code>, your_app_key<\/code>, your_app_secret<\/code>, and your_app_cluster<\/code> with your actual Pusher credentials. Save the file once done.<\/p>\nStep 4: Create Chatroom Model and Migration<\/h3>\n
Next, let’s create a Chatroom<\/code> model and a migration to store the chatroom details. Run the following command in your terminal:<\/p>\nphp artisan make:model Chatroom -m\n<\/code><\/pre>\nThis will create a new Chatroom<\/code> model and a migration file. Open the newly created migration file located in the database\/migrations<\/code> directory and update the up<\/code> method as follows:<\/p>\npublic function up()\n{\n Schema::create('chatrooms', function (Blueprint $table) {\n $table->id();\n $table->string('name');\n $table->timestamps();\n });\n}\n<\/code><\/pre>\nThis will create an id<\/code>, name<\/code>, and timestamps<\/code> columns in the chatrooms<\/code> table. Save the file once done.<\/p>\nStep 5: Create User Model and Migration<\/h3>\n
Next, let’s create a User<\/code> model and a migration file to store user details. Run the following command in your terminal:<\/p>\nphp artisan make:model User -m\n<\/code><\/pre>\nThis will create a new User<\/code> model and a migration file. Open the newly created migration file located in the database\/migrations<\/code> directory and update the up<\/code> method as follows:<\/p>\npublic function up()\n{\n Schema::create('users', function (Blueprint $table) {\n $table->id();\n $table->string('name');\n $table->string('email')->unique();\n $table->timestamp('email_verified_at')->nullable();\n $table->string('password');\n $table->rememberToken();\n $table->timestamps();\n });\n}\n<\/code><\/pre>\nThis will create the required columns in the users<\/code> table. Save the file once done.<\/p>\nStep 6: Create Chat Messages Model and Migration<\/h3>\n
Next, let’s create a ChatMessage<\/code> model and a migration file to store chat messages. Run the following command in your terminal:<\/p>\nphp artisan make:model ChatMessage -m\n<\/code><\/pre>\nThis will create a new ChatMessage<\/code> model and a migration file. Open the newly created migration file located in the database\/migrations<\/code> directory and update the up<\/code> method as follows:<\/p>\npublic function up()\n{\n Schema::create('chat_messages', function (Blueprint $table) {\n $table->id();\n $table->unsignedBigInteger('chatroom_id');\n $table->unsignedBigInteger('user_id');\n $table->text('message');\n $table->timestamps();\n });\n}\n<\/code><\/pre>\nThis will create the required columns in the chat_messages<\/code> table. Save the file once done.<\/p>\nStep 7: Run Migrations<\/h3>\n
Next, let’s run the migrations to create the required tables in the database. Run the following command in your terminal:<\/p>\n
php artisan migrate\n<\/code><\/pre>\nThis will create the chatrooms<\/code>, users<\/code>, and chat_messages<\/code> tables in your database.<\/p>\nStep 8: Create Routes<\/h3>\n
Now, let’s create some routes to handle the chat application functionality. Open the routes\/web.php<\/code> file located in the root directory of your Laravel project and update the file as follows:<\/p>\nuse AppHttpControllersChatController;\n\nRoute::get('\/', [ChatController::class, 'index'])->name('chat.index');\nRoute::post('\/message', [ChatController::class, 'sendMessage'])->name('chat.sendMessage');\nRoute::get('\/messages', [ChatController::class, 'getMessages'])->name('chat.getMessages');\n<\/code><\/pre>\nThis will define three routes for the chat application: \/<\/code> to display the chat interface, \/message<\/code> to send a message, and \/messages<\/code> to fetch the chat messages.<\/p>\nStep 9: Create Chat Controller<\/h3>\n
Next, let’s create a ChatController<\/code> to handle the chat application functionality. Run the following command in your terminal:<\/p>\nphp artisan make:controller ChatController\n<\/code><\/pre>\nThis will create a new ChatController<\/code> in the app\/Http\/Controllers<\/code> directory. Open the newly created ChatController<\/code> file and update the file as follows:<\/p>\nnamespace AppHttpControllers;\n\nuse AppModelsChatMessage;\nuse AppModelsChatroom;\nuse IlluminateHttpRequest;\n\nclass ChatController extends Controller\n{\n public function index()\n {\n $chatrooms = Chatroom::all();\n\n return view('chat.index', compact('chatrooms'));\n }\n\n public function sendMessage(Request $request)\n {\n $user = auth()->user();\n\n $message = $user->messages()->create([\n 'chatroom_id' => $request->input('chatroom_id'),\n 'message' => $request->input('message')\n ]);\n\n return response()->json($message);\n }\n\n public function getMessages()\n {\n $messages = ChatMessage::with('user')->latest()->limit(50)->get();\n\n return response()->json($messages);\n }\n}\n<\/code><\/pre>\nThis will define three methods in the ChatController<\/code>. The index<\/code> method returns the chat view, the sendMessage<\/code> method saves a new chat message to the database, and the getMessages<\/code> method returns the 50 latest chat messages.<\/p>\nStep 10: Create Chat Index View<\/h3>\n
Next, let’s create a chat index view. Run the following command in your terminal:<\/p>\n
mkdir resources\/views\/chat\ntouch resources\/views\/chat\/index.blade.php\n<\/code><\/pre>\nThis will create a new directory chat<\/code> in the resources\/views<\/code> directory and a new index.blade.php<\/code> file inside it. Open the index.blade.php<\/code> file and update the file as follows:<\/p>\n@extends('layouts.app')\n\n@section('content')\n <div class=\"container\">\n <div class=\"row\">\n <div class=\"col-md-3\">\n <h3>Chatrooms<\/h3>\n\n <ul>\n @foreach($chatrooms as $chatroom)\n <li>{{ $chatroom->name }}<\/li>\n @endforeach\n <\/ul>\n <\/div>\n <div class=\"col-md-9\">\n <h3>Chat<\/h3>\n\n <div id=\"chat-messages\"><\/div>\n\n <form>\n <div class=\"form-group\">\n <input type=\"text\" id=\"message-input\" class=\"form-control\" placeholder=\"Message\">\n <\/div>\n <button type=\"submit\" id=\"send-message\" class=\"btn btn-primary\">Send<\/button>\n <\/form>\n <\/div>\n <\/div>\n <\/div>\n@endsection\n\n@section('scripts')\n <script>\n var chatroomId = null;\n\n \/\/ Fetch chat messages\n function fetchMessages() {\n axios.get('\/messages')\n .then(function (response) {\n var chatMessages = '';\n\n response.data.forEach(function (message) {\n chatMessages += '<p><strong>' + message.user.name + '<\/strong>: ' + message.message + '<\/p>';\n });\n\n document.getElementById('chat-messages').innerHTML = chatMessages;\n })\n .catch(function (error) {\n console.log(error);\n });\n }\n\n \/\/ Send chat message\n function sendMessage(event) {\n event.preventDefault();\n\n var message = document.getElementById('message-input').value;\n\n if (chatroomId && message) {\n axios.post('\/message', { chatroom_id: chatroomId, message: message })\n .then(function (response) {\n \/\/ Clear input field\n document.getElementById('message-input').value = '';\n\n \/\/ Fetch messages again\n fetchMessages();\n })\n .catch(function (error) {\n console.log(error);\n });\n }\n }\n\n \/\/ Event Listeners\n document.getElementById('send-message').addEventListener('click', sendMessage);\n\n \/\/ Fetch messages on page load\n window.addEventListener('DOMContentLoaded', function () {\n fetchMessages();\n });\n <\/script>\n@endsection\n<\/code><\/pre>\nThis will create the chat index view with a list of chatrooms, a chat window, and a form to send messages. The JavaScript code handles fetching and displaying chat messages, sending messages, and updating the chat window in real-time.<\/p>\n
Step 11: Update Layout<\/h3>\n
Open the resources\/views\/layouts\/app.blade.php<\/code> file and update the file as follows:<\/p>\n<!DOCTYPE html>\n<html lang=\"{{ str_replace('_', '-', app()->getLocale()) }}\">\n<head>\n <meta charset=\"utf-8\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n\n <title>{{ config('app.name', 'Laravel') }}<\/title>\n\n <link href=\"{{ asset('css\/app.css') }}\" rel=\"stylesheet\">\n<\/head>\n<body>\n <div id=\"app\">\n <nav class=\"navbar navbar-expand-md navbar-light bg-white shadow-sm\">\n <div class=\"container\">\n <a class=\"navbar-brand\" href=\"{{ url('\/') }}\">\n {{ config('app.name', 'Laravel') }}\n <\/a>\n <button class=\"navbar-toggler\" type=\"button\" data-toggle=\"collapse\" data-target=\"#navbarSupportedContent\" aria-controls=\"navbarSupportedContent\" aria-expanded=\"false\" aria-label=\"{{ __('Toggle navigation') }}\">\n <span class=\"navbar-toggler-icon\"><\/span>\n <\/button>\n\n <div class=\"collapse navbar-collapse\" id=\"navbarSupportedContent\">\n <!-- Left Side Of Navbar -->\n <ul class=\"navbar-nav mr-auto\">\n\n <\/ul>\n\n <!-- Right Side Of Navbar -->\n <ul class=\"navbar-nav ml-auto\">\n <!-- Authentication Links -->\n @guest\n @if (Route::has('login'))\n <li class=\"nav-item\">\n <a class=\"nav-link\" href=\"{{ route('login') }}\">{{ __('Login') }}<\/a>\n <\/li>\n @endif\n\n @if (Route::has('register'))\n <li class=\"nav-item\">\n <a class=\"nav-link\" href=\"{{ route('register') }}\">{{ __('Register') }}<\/a>\n <\/li>\n @endif\n @else\n <li class=\"nav-item dropdown\">\n <a id=\"navbarDropdown\" class=\"nav-link dropdown-toggle\" href=\"#\" role=\"button\" data-toggle=\"dropdown\" aria-haspopup=\"true\" aria-expanded=\"false\" v-pre>\n {{ Auth::user()->name }}\n <\/a>\n\n <div class=\"dropdown-menu dropdown-menu-right\" aria-labelledby=\"navbarDropdown\">\n <a class=\"dropdown-item\" href=\"{{ route('logout') }}\"\n onclick=\"event.preventDefault();\n document.getElementById('logout-form').submit();\">\n {{ __('Logout') }}\n <\/a>\n\n <form id=\"logout-form\" action=\"{{ route('logout') }}\" method=\"POST\" class=\"d-none\">\n @csrf\n <\/form>\n <\/div>\n <\/li>\n @endguest\n <\/ul>\n <\/div>\n <\/div>\n <\/nav>\n\n <main class=\"py-4\">\n @yield('content')\n <\/main>\n <\/div>\n\n <script src=\"{{ asset('js\/app.js') }}\"><\/script>\n @yield('scripts')\n<\/body>\n<\/html>\n<\/code><\/pre>\nThis will update the layout file to include the required JavaScript and CSS assets.<\/p>\n
Step 12: Run Laravel Development Server<\/h3>\n
Finally, let’s run the Laravel development server to see our chat application in action. Run the following command in your terminal:<\/p>\n
php artisan serve\n<\/code><\/pre>\nThis will start the Laravel development server on `http:\/\/localhost:8000`. Visit this URL in your browser to see the chat application.<\/p>\n
Congratulations! You have successfully built a chat application with Laravel Echo and Pusher. Users can now send and receive messages in real-time.<\/p>\n
Conclusion<\/h3>\n
In this tutorial, we learned how to build a real-time chat application using Laravel Echo and Pusher. We covered the following steps:<\/p>\n
\n- Setting up a new Laravel project<\/li>\n
- Installing Laravel Echo and Pusher<\/li>\n
- Configuring Laravel Echo<\/li>\n
- Creating models and migrations for chatrooms, users, and chat messages<\/li>\n
- Running migrations<\/li>\n
- Creating routes and a controller<\/li>\n
- Creating chat views and updating the layout<\/li>\n
- Running the Laravel development server<\/li>\n<\/ul>\n
Now, you can further enhance your chat application with features like private messaging, online\/offline status, and message notifications.<\/p>\n","protected":false},"excerpt":{"rendered":"
How to Build a Chat Application with Laravel Echo and Pusher In this tutorial, we will learn how to build a real-time chat application using Laravel Echo and Pusher. Laravel Echo is a JavaScript library that makes it easy to handle real-time events in Laravel applications. Pusher is a hosted Continue Reading<\/a><\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"closed","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_import_markdown_pro_load_document_selector":0,"_import_markdown_pro_submit_text_textarea":"","footnotes":""},"categories":[1],"tags":[1178,1177,1180,1176,1179,680,49,1175],"yoast_head":"\nHow to Build a Chat Application with Laravel Echo and Pusher - Pantherax Blogs<\/title>\n\n\n\n\n\n\n\n\n\n\n\n\n\n\t\n\t\n\t\n