Laravel chat message module using socket.io and nodejs

Share Me
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  

Today now in this post, i will go to show you a example of how to make real time chat message module by using socket.io, redis, express and nodejs in Laravel application. We know that socket.io through we can make a real time chat module in our Laravel application. So now here i will show you this from the scratch because you need to install nodejs and its packages etc. From this post you can understand and also learn step by installing and how to write code. Now we have to follow the bellow step and need to implement real time chat module in our application.

Step 1: Install nodejs

At first in this step we need install nodejs if we did not install before in our environment . So, make sure we can check if nodejs is install or not . If not then we can fire the following command and install nodejs easily.

sudo apt-get update
sudo apt-get install nodejs
Step 2: Install npm

Now we also need to install npm because we will also need to install more socket.io, redis and express package by using npm command, so if we have not installed this command before then install by the following command.

sudo apt-get install npm
Step 3: Install Redis-server

So we also need to install redis server because we will manage the redis token, so if we did not installed before then need to install by following command.

sudo apt-get install redis-server
Step 4: Install express redis socket.io

Again we also require to install the redis express redis socket.io, so if we did not installed before then need to install by following command.

npm install express redis socket.io --save
Step 5: Install Laravel

Good , now we are ready for install laravel application, so if we want to start from the scratch then need to fire following command for laravel new application.

composer create-project --prefer-dist laravel/laravel blog
Step 6: Create server.js file

So now, need open laravel application root directory and then need create a folder nodejs and also need to create new file server.js inside nodejs folder, so then put bellow code in server.js file.

nodejs/server.js

var app = require('express')();
var server = require('http').Server(app);
var io = require('socket.io')(server);
var redis = require('redis');
 
server.listen(8890);
io.on('connection', function (socket) {
 
  console.log("client connected");
  var redisClient = redis.createClient();
  redisClient.subscribe('message');
 
  redisClient.on("message", function(channel, data) {
    console.log("mew message add in queue "+ data['message'] + " channel");
    socket.emit(channel, data);
  });
 
  socket.on('disconnect', function() {
    redisClient.quit();
  });
 
});
Step 7: Install predis package

Now in this step we need to install predis package in our laravel application. So this package through we can assign message in redis. So at first need to fire following command:

sudo composer require predis/predis

Now we need to add aliase of predis package so now open config/app.php and replace following line:

'Redis'     => Illuminate\Support\Facades\Redis::class,

Replace Into

'LRedis'    => 'Illuminate\Support\Facades\Redis'
Step 8: Add Auth and Controller

So now we have to need authentication module for this real chat system because without any login use we can’t chat each other, so at first need to fire following command.

php artisan make:auth

Ok, now we need to run migration that way we can create users table:

php artisan migrate

And we also need to create a new chatController controller so, need to fire bellow command for create new chatController.

php artisan make:controller chatController

Put bellow code in that controller.

app/Http/Controllers/chatController

namespace App\Http\Controllers;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use Request;
use LRedis;
 
class chatController extends Controller {
	public function __construct()
	{
		$this->middleware('guest');
	}
	public function sendMessage(){
		$redis = LRedis::connection();
		$data = ['message' => Request::input('message'), 'user' => Request::input('user')];
		$redis->publish('message', json_encode($data));
		return response()->json([]);
	}
}
Step 9: Add Route and Message Layout

So now we are in the last step, we need to following route, so open your routes.php file and then add following route.

Route::group(['middleware' => 'web'], function () {
    Route::auth();
    Route::get('/home', '[email protected]');
});
Route::post('sendmessage', '[email protected]');

Okay next, we need to replace resources/views/home.blade.php file. So need to copy bellow code and put in this file:

resources/views/home.blade.php

@extends('layouts.app')
@section('content')
<script src="//code.jquery.com/jquery-1.11.2.min.js"></script>
<script src="//code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
<script src="https://cdn.socket.io/socket.io-1.3.4.js"></script>
<style type="text/css">
    #messages{
        border: 1px solid black;
        height: 300px;
        margin-bottom: 8px;
        overflow: scroll;
        padding: 5px;
    }
</style>
<div class="container spark-screen">
    <div class="row">
        <div class="col-md-10 col-md-offset-1">
            <div class="panel panel-default">
                <div class="panel-heading">Chat Message Module</div>
                <div class="panel-body">
 
                <div class="row">
                    <div class="col-lg-8" >
                      <div id="messages" ></div>
                    </div>
                    <div class="col-lg-8" >
                            <form action="sendmessage" method="POST">
                                <input type="hidden" name="_token" value="{{ csrf_token() }}" >
                                <input type="hidden" name="user" value="{{ Auth::user()->name }}" >
                                <textarea class="form-control msg"></textarea>
                                <br/>
                                <input type="button" value="Send" class="btn btn-success send-msg">
                            </form>
                    </div>
                </div>
                </div>
            </div>
        </div>
    </div>
</div>
<script>
    var socket = io.connect('http://localhost:8890');
    socket.on('message', function (data) {
        data = jQuery.parseJSON(data);
        console.log(data.user);
        $( "#messages" ).append( "<strong>"+data.user+":</strong><p>"+data.message+"</p>" );
      });
    $(".send-msg").click(function(e){
        e.preventDefault();
        var token = $("input[name='_token']").val();
        var user = $("input[name='user']").val();
        var msg = $(".msg").val();
        if(msg != ''){
            $.ajax({
                type: "POST",
                url: '{!! URL::to("sendmessage") !!}',
                dataType: "json",
                data: {'_token':token,'message':msg,'user':user},
                success:function(data){
                    console.log(data);
                    $(".msg").val('');
                }
            });
        }else{
            alert("Please Add Message.");
        }
    })
</script>
@endsection

Ok, finally we are totally ready to run this script, So at first open your terminal and then go on nodejs directory then fire the following command.

node server.js

Read Also : How to Create Custom Blade Directive in Laravel?

Thanks for read. I hope it help you. For more you can follow us on facebook.

About code chef

My name is Shahriar sagor. I'm a developer. I live in Bangladesh and I love to write tutorials and tips that will help to other Developer's. I am a big fan of PHP, Javascript, JQuery, Laravel, Codeigniter, VueJS, AngularJS and Bootstrap from the early stage.

View all posts by code chef →