Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/mosesesan/mesan-laravel-socketio
Project using Laravel 5.3 and Socket.io for sending real time messages
https://github.com/mosesesan/mesan-laravel-socketio
laravel nodejs-server php redis
Last synced: 2 months ago
JSON representation
Project using Laravel 5.3 and Socket.io for sending real time messages
- Host: GitHub
- URL: https://github.com/mosesesan/mesan-laravel-socketio
- Owner: MosesEsan
- Created: 2016-12-15T21:33:19.000Z (about 8 years ago)
- Default Branch: master
- Last Pushed: 2022-12-06T14:57:58.000Z (about 2 years ago)
- Last Synced: 2024-04-20T14:34:29.022Z (9 months ago)
- Topics: laravel, nodejs-server, php, redis
- Language: PHP
- Size: 322 KB
- Stars: 6
- Watchers: 4
- Forks: 9
- Open Issues: 24
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
# Laravel 5.3 Project using Socket.io for sending real time messages
Steps
- Step 0: Install Node and Redis
- Step 1: Setup and Dependecies
- Step 2: Prepare the Database
- Step 3: Create Model
- Step 4: Create Controller
- Step 5: Set up route
- Step 6: Create View
- Step 7: Create Server File
- Step 8: Test and Run
Step 0: Install Node and Redis
To make possible the communication from the two different backend servers, Laravel 5 and NodeJS we will use Redis.
Redis is a key value storage with a publish/subscriber feature.
Basically every message published on a specific queue will be intercepted from every subscriber, in this case the subscriber will be the NodeJS server.
Make sure you have node installed: Node
Mac
If you have brew you can install redis easily by running this command
Run
```bash
brew install redis
```
Then, to start the server
Run
```bash
redis-server
```
Step 1: Setup and Dependencies
Install Socket.io, Express, redis
Run
```bash
npm install socket.io express redis --save
```
Open composer.json and update the require object to include entrust:
```php
"require": {
"php": ">=5.6.4",
"laravel/framework": "5.3.*",
"predis/predis": "^1.1"
},
```
Then, run
```bash
composer update
```
To avoid conflict with Redis in PHP environment we will modify also the alias to the Redis module of Laravel. In the config config/app.php file change
```php
'Redis' => 'Illuminate\Support\Facades\Redis',
```
to
```php
'LRedis' => 'Illuminate\Support\Facades\Redis',
```
Step 2: Prepare the Database
For Authentication, run
```bash
php artisan make:auth
```
Update .env file with your database settings(db_database, db_username, db_password)
```php
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=[db_name]
DB_USERNAME=[db_user]
DB_PASSWORD=[db_pwd]
```
If you install a fresh laravel project then you have already users table migration.
You need to create the messages table.
```bash
php artisan make:migration create_messages_table
```
messages
```php
increments('id');
$table->integer('user_id')->unsigned();
$table->text('message');
$table->timestamps();
$table->foreign('user_id')->references('id')->on('users');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('messages');
}
}
```
Run
```bash
php artisan migrate
```
Step 3: Create Model for Message
Run
```bash
php artisan make:model Message
```
```php
Step 4: Create Controller
Run
```bash
php artisan make:controller SocketController
```
```php
on('messages.user_id', '=', 'users.id');
})->select(
'users.name', 'messages.message')->orderBy('messages.created_at', 'asc')
->get();
return view('writemessage', compact('messages'));
}
//Send Message
public function sendMessage(Request $request)
{
$user = Auth::user();
$input = $request->all();
$redis = LRedis::connection();
if(!isset($input['message']) || trim($input['message']) === ''){
}else{
Message::create([
'user_id' => $user->id,
'message' => $input['message']
]);
$data = ['message' => $input['message'], 'user' => $user->name];
$redis->publish('message', json_encode($data));
}
}
}
```
Step 5: Set up route
```php
['auth']], function() {
Route::get('writemessage', ['as'=>'writemessage','uses'=>'SocketController@writemessage']);
Route::post('sendmessage', 'SocketController@sendMessage');
});
```
Step 6: Create View
resources/views/writemessage.blade.php
```php
@extends('layouts.app')
@section('content')
@foreach ($messages as $key => $message)
{{$message->first_name}} : {{$message->message}}
@endforeach
{{ csrf_field() }}
var socket = io.connect('http://localhost:8890');
socket.on('message', function (data) {
data = JSON.parse(data);
$( "#messages" ).append( "<p>"+data.user+" : "+data.message+"</p>" );
});
$('input.send').click(function(e){
e.preventDefault();
search();
});
function search() {
var message = $('input.message').val();
$.ajax({
type: "POST",
url: "sendmessage",
data: { "_token": $('meta[name="csrf-token"]').attr('content'), "message": message},
cache: false,
success: function(results){
}
});
}
@endsection
```
Step 7: Create Server File
In the project root folder create a new file server.js file
```javascript
var app = require('express')();
var server = require('http').Server(app);
var io = require('socket.io')(server);
var redis = require('redis');
var port_number = 8890;
server.listen(port_number, function(){
console.log("Listening on "+port_number)
});
io.on('connection', function (socket) {
console.log("new client connected");
var redisClient = redis.createClient();
redisClient.subscribe('message');
redisClient.on("message", function(channel, message) {
console.log("new message in queue "+ message + "channel");
socket.emit(channel, message);
});
socket.on('disconnect', function() {
redisClient.quit();
});
});
```
Step 8: Test and Run
In the project root folder create a new file server.js file
To test the application you can start the Redis and NodeJS server.
In terminal run:
```bash
redis-server
```
In your project root folder run:
```bash
node server.js
```
In your project root folder run: node server.js
Login into you app and test by sending a message