Laravel 5.2 chat message module using socket.io, redis, express and nodejs from from scratch.
In this tutorial, i going to show you how to make real time chat message module using socket.io, redis, express and nodejs in Laravel 5. socket.io through we can make real time chat module in our Laravel 5 application. i show you from scratch because you can install nodejs and its packages etc. in this post you can undestand and learn step by istalling and how to write code. You have to follow the step and implement real time chat module in your application. So basically you can see bellow preview of our chat message module.
Preview:
Step 1: Install nodejs
in first step we will install nodejs if we did not install before. So, make sure you can check if nodejs is not install then you can fire following command and install nodejs easily.
sudo apt-get update
sudo apt-get install nodejs
Step 2: Install npm
we have to also need to install npm because we will install more socket.io, redis and express package using npm command, so if you not installed this command before then install by following command.
sudo apt-get install npm
Step 3: Install Redis-server
we also require to install redis server because we will manage redis token, so if you not installed this command before then install by following command.
sudo apt-get install redis-server
Step 4: Install express redis socket.io
we also require to install redis express redis socket.io, so if you not installed this command before then install by following command.
npm install express redis socket.io --save
Step 5: Install Laravel
ok, now we are ready to install laravel 5 application, so if you want to start from scratch then fire following command for laravel new application.
composer create-project --prefer-dist laravel/laravel blog
Step 6: Create server.js file
Now, open laravel application root directory and create folder nodejs and also create new file server.js inside nodejs folder, so 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
In this step we have to install predis package off laravel. this package through we can assign message in redis. so first fire following command:
sudo composer require predis/predis
now we have to add aliase of predis package so 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
we have to need authentication module for this real chat system because without login use we can't chat each other, so first fire following command.
php artisan make:auth
You can see in your terminal like this way:
Created View: /var/www/laravel5/resources/views/auth/login.blade.php
Created View: /var/www/laravel5/resources/views/auth/register.blade.php
Created View: /var/www/laravel5/resources/views/auth/passwords/email.blade.php
Created View: /var/www/laravel5/resources/views/auth/passwords/reset.blade.php
Created View: /var/www/laravel5/resources/views/auth/emails/password.blade.php
Created View: /var/www/laravel5/resources/views/layouts/app.blade.php
Created View: /var/www/laravel5/resources/views/home.blade.php
Created View: /var/www/laravel5/resources/views/welcome.blade.php
Installed HomeController.
Updated Routes File.
Authentication scaffolding generated successfully!
Ok, now run migration that way we can create users table:
php artisan migrate
And we also need to create new chatController controller so, 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
in this last step, we need to following route, so open your routes.php file and add following route.
Route::group(['middleware' => 'web'], function () {
Route::auth();
Route::get('/home', 'HomeController@index');
});
Route::post('sendmessage', 'chatController@sendMessage');
next, we have to replace resources/views/home.blade.php file. so 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 ready to run this script, so first open your terminal and go on nodejs directory then fire following command.
node server.js
Now run application on your browser and run.
IF you want to download this from git then you can download from here GitHub
Hardik Savani
I'm a full-stack developer, entrepreneur and owner of ItSolutionstuff.com. I live in India and I love to write tutorials and tips that can help to other artisan. I am a big fan of PHP, Laravel, Angular, Vue, Node, Javascript, JQuery, Codeigniter and Bootstrap from the early stage. I believe in Hardworking and Consistency.