Make real-time chat system with Laravel

Communication performs a very important role in every business website. Example: If customers will communicate easily to us, then they can get better knowledge for our product and we can also solve their queries easily. But if they can’t communication with us, then they will not get better knowledge and not satisfy with our product.

To fix this problem, we can add communication tool to our website. Chat system is very effective way to communicate easily. In this blog, we will see how to make a real-time chat system with laravel framework.

If you don’t have knowledge that: how to install laravel, then you can follow bellow steps:

  • Install composer in your system. (follow the steps given in this link: )
  • Run below command in the terminal(or cmd), where you want to make the laravel app.
composer create-project laravel/laravel chat_system
  • Above command will make a new Laravel project folder with name: “chat_system”. you can replace “chat_system” to any name you want.
  • Go to the project folder and run the project with the below commands:
cd chat_system
php artisan serve

Open this URL in the browser: http://localhost:8000 . You can see the output something like this

Now, we will install one laravel’s package to make chat system. The name of that package is: “pusher”. Follow below steps to install “pusher” in your laravel app:

Pusher Installation

We have split the installation process in 2 group: “Back-end”, and “Front-end”.

Back-end Side Installation

  • Run composer require pusher/pusher-php-server in root folder
  • Make your pusher account at https://pusher.com/
  • Copy the app credentials into .env file
  • Change the env variable BROADCAST_DRIVER to pusher
  • Uncomment BroadcastServiceProvider in your config/app.php
  • Add route in api.php
Route::post('/message', 'App\Http\Controllers\ChatController@index');
  • Make Event using this command: php artisan make:event MessageSend. And Copy the below code in newly created file: app/Events/MessageSend.php.
<?php

namespace App\Events;

use Illuminate\Broadcasting\Channel;
use Illuminate\Queue\SerializesModels;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;

class MessageSend implements ShouldBroadcast
{
    use Dispatchable, InteractsWithSockets, SerializesModels;

    public $message;

    public function __construct($message)
    {
        $this->message = $message;
    }

    public function broadcastOn()
    {
        return new Channel('chatbox');
    }
}
  • Make a file under controller folder with name “ChatController”, and put below code in that file:
<?php

namespace App\Http\Controllers;

use App\Events\MessageSend;
use Illuminate\Http\Request;

class ChatController extends Controller
{
    public function index(Request $request)
    {
        $message = $request->input('message', '');

        if (strlen($message)) {
            event(new MessageSend($message));
        }
    }
}

Front-end

  • Install pusher js library: npm install --save laravel-echo pusher-js
  • Install laravel UI using this command: composer require laravel/ui
  • Install VUE using this command: php artisan ui vue
  • Uncomment import Echo from 'laravel-echo'; line and all the below code in /resources/js/bootstrap.js file
  • Uncomment this code in your /resources/js/app.js file
const files = require.context('./', true, /\.vue$/i)
files.keys().map(key => Vue.component(key.split('/').pop().split('.')[0], files(key).default))
  • Make ChatboxComponent.vue file /resources/js/components/ path and copy the below code into it.
<template>
    <div class="chatbox p-3">
        <div class="messages" v-if="messages.length">
            <div class="message" v-for="message in messages">
                <span class="d-inline-block">{{ message }}</span>
            </div>
        </div>

        <div class="row mt-5">
            <div class="col-3">
                <input type="text" class="form-control" v-model="textMessage"></input>
            </div>
        </div>

        <div class="row mt-2">
            <div class="col">
                <button class="btn btn-primary" @click="sendMessage()">Send</button>
            </div>
        </div>
    </div>
</template>

<script>
    export default {
        data() {
            return {
                textMessage: '',
                messages: [],
            }
        },
        created() {
            this.addMessage('You joined the chatbox.');
            Echo.channel('chatbox')
                .listen('MessageSend', (e) => {
                    this.addMessage(e.message);
                });
        },
        methods: {
            addMessage(message) {
                let date= new Date();
                let timestamp = date.getHours() + ':' + date.getMinutes() + ':' + date.getSeconds();
                this.messages.push(timestamp + ' ' + message);
            },
            sendMessage() {
                axios.post('/api/message', {message: this.textMessage});
                this.textMessage = '';
            }
        }
    }
</script>
  • Make the view file with name chat.blade.php and copy below code into that file.
<!doctype html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <meta name="csrf-token" content="{{ csrf_token() }}">
        <title>Chatbox</title>

        <script src="{{ asset('js/app.js') }}" defer></script>
        <script src="{{ asset('js/jquery.js') }}"></script>
        <script src="{{ asset('js/bootstrap.min.js') }}"></script>
        <link href="{{ asset('css/app.css') }}" rel="stylesheet">
    </head>
    <body>
        <div id="app">
            <chatbox-component></chatbox-component>
        </div>
    </body>
</html>
  • add route in web.php
Route::get('customer_chat',function(){
    return view('chat');
});
  • Install mix for compiling our code. run this command:  npm install laravel-mix@latest
  • Run npm run watch
  • Finally. run php artisan serve command.
  • Your chat system will be display in this URL: http://localhost:8000/customer_chat
  • Open this link in 2 different browsers and send a message from one browser. You can see that message will be added in another browser also.
Share this:

Related Post

Surprising Things You Might Not Know About Laravel

Surprising Things You Might Not Know About Laravel

How To Publish Laravel Package On Packagist?

How To Publish Laravel Package On Packagist?

How To Make Custom Laravel Package Using Composer?

How To Make Custom Laravel Package Using Composer?