{"id":20159615,"url":"https://github.com/mosesesan/mesan-laravel-socketio","last_synced_at":"2025-04-09T23:36:32.657Z","repository":{"id":51708154,"uuid":"76597890","full_name":"MosesEsan/mesan-laravel-socketio","owner":"MosesEsan","description":"Project using Laravel 5.3 and Socket.io for sending real time messages","archived":false,"fork":false,"pushed_at":"2022-12-06T14:57:58.000Z","size":330,"stargazers_count":6,"open_issues_count":24,"forks_count":9,"subscribers_count":3,"default_branch":"master","last_synced_at":"2025-03-24T01:25:26.846Z","etag":null,"topics":["laravel","nodejs-server","php","redis"],"latest_commit_sha":null,"homepage":null,"language":"PHP","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/MosesEsan.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2016-12-15T21:33:19.000Z","updated_at":"2021-07-26T11:41:44.000Z","dependencies_parsed_at":"2023-01-23T09:46:09.859Z","dependency_job_id":null,"html_url":"https://github.com/MosesEsan/mesan-laravel-socketio","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/MosesEsan%2Fmesan-laravel-socketio","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/MosesEsan%2Fmesan-laravel-socketio/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/MosesEsan%2Fmesan-laravel-socketio/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/MosesEsan%2Fmesan-laravel-socketio/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/MosesEsan","download_url":"https://codeload.github.com/MosesEsan/mesan-laravel-socketio/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":248130875,"owners_count":21052816,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["laravel","nodejs-server","php","redis"],"created_at":"2024-11-14T00:09:12.259Z","updated_at":"2025-04-09T23:36:32.641Z","avatar_url":"https://github.com/MosesEsan.png","language":"PHP","funding_links":[],"categories":[],"sub_categories":[],"readme":"# Laravel 5.3 Project using Socket.io for sending real time messages\n\n\u003ch1\u003eSteps\u003c/h1\u003e\n\n\u003cul\u003e\n  \u003cli\u003e\u003ca href=\"#step0\"\u003eStep 0: Install Node and Redis \u003c/a\u003e\u003c/li\u003e\n  \u003cli\u003e\u003ca href=\"#step1\"\u003eStep 1: Setup and Dependecies \u003c/a\u003e\u003c/li\u003e\n  \u003cli\u003e\u003ca href=\"#step2\"\u003eStep 2: Prepare the Database\u003c/a\u003e\u003c/li\u003e\n  \u003cli\u003e\u003ca href=\"#step3\"\u003eStep 3: Create Model\u003c/a\u003e\u003c/li\u003e\n  \u003cli\u003e\u003ca href=\"#step4\"\u003eStep 4: Create Controller\u003c/a\u003e\u003c/li\u003e\n  \u003cli\u003e\u003ca href=\"#step5\"\u003eStep 5: Set up route\u003c/a\u003e\u003c/li\u003e\n  \u003cli\u003e\u003ca href=\"#step6\"\u003eStep 6: Create View\u003c/a\u003e\u003c/li\u003e\n  \u003cli\u003e\u003ca href=\"#step7\"\u003eStep 7: Create Server File\u003c/a\u003e\u003c/li\u003e\n  \u003cli\u003e\u003ca href=\"#step8\"\u003eStep 8: Test and Run\u003c/a\u003e\u003c/li\u003e\n\u003c/ul\u003e\n\n\n\u003ca name=\"step0\"\u003e\u003c/a\u003e\n\u003ch1\u003eStep 0: Install Node and Redis\u003c/h1\u003e\n\nTo make possible the communication from the two different backend servers, Laravel 5 and NodeJS we will use Redis.\nRedis is a key value storage with a publish/subscriber feature.\nBasically every message published on a specific queue will be intercepted from every subscriber, in this case the subscriber will be the NodeJS server.\n\n\u003cb\u003eMake sure you have node installed\u003c/b\u003e: \u003ca href=\"https://nodejs.org/en/\"\u003eNode\u003c/a\u003e\n\n\u003cb\u003eMac\u003c/b\u003e\nIf you have brew you can install redis easily by running this command\nRun\n```bash\nbrew install redis\n```\n\nThen, to start the server\nRun\n```bash\nredis-server\n```\n\n\u003ca name=\"step1\"\u003e\u003c/a\u003e\n\u003ch1\u003eStep 1: Setup and Dependencies\u003c/h1\u003e\n\nInstall Socket.io, Express, redis\n\nRun\n```bash\nnpm install socket.io express redis --save\n```\n\nOpen composer.json and update the require object to include entrust:\n```php\n\"require\": {\n    \"php\": \"\u003e=5.6.4\",\n    \"laravel/framework\": \"5.3.*\",\n    \"predis/predis\": \"^1.1\"\n},\n```\n\nThen, run\n```bash\ncomposer update\n```\n\nTo avoid conflict with Redis in PHP environment we will modify also the alias to the Redis module of Laravel. In the config \u003cb\u003econfig/app.php\u003c/b\u003e file change\n\n```php\n'Redis'    =\u003e 'Illuminate\\Support\\Facades\\Redis',\n```\n\nto\n\n```php\n'LRedis'    =\u003e 'Illuminate\\Support\\Facades\\Redis',\n```\n\n\u003ca name=\"step2\"\u003e\u003c/a\u003e\n\u003ch1\u003eStep 2: Prepare the Database\u003c/h1\u003e\n\nFor Authentication, run\n```bash\nphp artisan make:auth\n```\n\nUpdate .env file with your database settings(db_database, db_username, db_password)\n\n```php\nDB_CONNECTION=mysql\nDB_HOST=127.0.0.1\nDB_PORT=3306\nDB_DATABASE=[db_name]\nDB_USERNAME=[db_user]\nDB_PASSWORD=[db_pwd]\n```\n\n\nIf you install a fresh laravel project then you have already users table migration.\n\nYou need to create the messages table.\n```bash\nphp artisan make:migration create_messages_table\n\n```\n\n\u003cstrong\u003emessages\u003c/strong\u003e\n```php\n\u003c?php\n\nuse Illuminate\\Database\\Schema\\Blueprint;\nuse Illuminate\\Database\\Migrations\\Migration;\n\nclass CreateMessagesTable extends Migration\n{\n     /**\n      * Run the migrations.\n      *\n      * @return void\n      */\n     public function up()\n     {\n         Schema::create('messages', function (Blueprint $table) {\n             $table-\u003eincrements('id');\n             $table-\u003einteger('user_id')-\u003eunsigned();\n             $table-\u003etext('message');\n             $table-\u003etimestamps();\n\n            $table-\u003eforeign('user_id')-\u003ereferences('id')-\u003eon('users');\n         });\n     }\n\n    /**\n      * Reverse the migrations.\n      *\n      * @return void\n      */\n     public function down()\n     {\n         Schema::drop('messages');\n     }\n}\n```\n\nRun\n```bash\nphp artisan migrate\n```\n\n\u003ca name=\"step3\"\u003e\u003c/a\u003e\n\u003ch1\u003eStep 3: Create Model for Message\u003c/h1\u003e\n\nRun\n```bash\nphp artisan make:model Message\n```\n\n```php\n\u003c?php\n\nnamespace App;\n\nuse Illuminate\\Database\\Eloquent\\Model;\n\nclass Message extends Model\n{\n    /**\n     * The attributes that are mass assignable.\n     *\n     * @var array\n     */\n    protected $fillable = [\n        'user_id', 'message'\n    ];\n\n}\n```\n\n\n\u003ca name=\"step4\"\u003e\u003c/a\u003e\n\u003ch1\u003eStep 4: Create Controller\u003c/h1\u003e\n\nRun\n```bash\nphp artisan make:controller SocketController\n```\n\n```php\n\u003c?php\n\n\tnamespace App\\Http\\Controllers;\n\n\tuse Illuminate\\Http\\Request;\n\n\tuse App\\Http\\Requests;\n\tuse App\\Http\\Controllers\\Controller;\n\tuse LRedis, Auth;\n\n\tuse App\\Message;\n\n\tclass SocketController extends Controller\n\t{\n\t    //Write Message\n\t    public function writemessage()\n\t    {\n\t        $messages = Message::leftJoin('users', function($join) {\n\t            $join-\u003eon('messages.user_id', '=', 'users.id');\n\t        })-\u003eselect(\n\t            'users.name', 'messages.message')-\u003eorderBy('messages.created_at', 'asc')\n\t            -\u003eget();\n\n\t        return view('writemessage', compact('messages'));\n\t    }\n\n\t    //Send Message\n\t    public function sendMessage(Request $request)\n\t    {\n\t        $user = Auth::user();\n\n\t        $input = $request-\u003eall();\n\t        $redis = LRedis::connection();\n\n\t        if(!isset($input['message']) || trim($input['message']) === ''){\n\t        }else{\n\t            Message::create([\n\t                'user_id' =\u003e $user-\u003eid,\n\t                'message' =\u003e $input['message']\n\t            ]);\n\n\t            $data = ['message' =\u003e $input['message'], 'user' =\u003e $user-\u003ename];\n\t            $redis-\u003epublish('message', json_encode($data));\n\t        }\n\t    }\n\t}\n```\n\n\u003ca name=\"step5\"\u003e\u003c/a\u003e\n\u003ch1\u003eStep 5: Set up route\u003c/h1\u003e\n\n```php\n\u003c?php\n\nRoute::group(['middleware' =\u003e ['auth']], function() {\n    Route::get('writemessage', ['as'=\u003e'writemessage','uses'=\u003e'SocketController@writemessage']);\n    Route::post('sendmessage', 'SocketController@sendMessage');\n});\n```\n\n\u003ca name=\"step6\"\u003e\u003c/a\u003e\n\u003ch1\u003eStep 6: Create View\u003c/h1\u003e\n\n\n\u003cstrong\u003eresources/views/writemessage.blade.php\u003c/strong\u003e\n\n```php\n@extends('layouts.app')\n\n@section('content')\n    \u003cscript src=\"//code.jquery.com/jquery-1.11.2.min.js\"\u003e\u003c/script\u003e\n    \u003cscript src=\"//code.jquery.com/jquery-migrate-1.2.1.min.js\"\u003e\u003c/script\u003e\n    \u003cscript src=\"https://cdn.socket.io/socket.io-1.3.4.js\"\u003e\u003c/script\u003e\n\n    \u003cdiv class=\"container\"\u003e\n        \u003cdiv class=\"row\"\u003e\n            \u003cdiv class=\"col-lg-8 col-lg-offset-2\" \u003e\n                \u003cdiv class=\"panel panel-default\"\u003e\n                    \u003cdiv class=\"panel-heading\"\u003eMessages Received\u003c/div\u003e\n                    \u003cdiv id=\"messages\" style=\"height: 250px;     padding: 15px;\"\u003e\n\n                        @foreach ($messages as $key =\u003e $message)\n                            \u003cp\u003e{{$message-\u003efirst_name}} : {{$message-\u003emessage}}\u003c/p\u003e\n                        @endforeach\n\n                    \u003c/div\u003e\n                \u003c/div\u003e\n            \u003c/div\u003e\n        \u003c/div\u003e\n        \u003cdiv class=\"row\"\u003e\n            \u003cdiv class=\"col-md-10 col-md-offset-1\"\u003e\n                \u003cdiv class=\"panel panel-default\"\u003e\n                    \u003cdiv class=\"panel-heading\"\u003eSend message\u003c/div\u003e\n                    \u003cform action=\"sendmessage\" method=\"POST\"\u003e\n                        {{ csrf_field() }}\n                        \u003cinput type=\"text\" name=\"message\" class=\"message\" \u003e\n                        \u003cinput type=\"submit\" value=\"send\" class=\"send\"\u003e\n                    \u003c/form\u003e\n                \u003c/div\u003e\n            \u003c/div\u003e\n        \u003c/div\u003e\n    \u003c/div\u003e\n\n    \u003cscript\u003e\n        var socket = io.connect('http://localhost:8890');\n        socket.on('message', function (data) {\n            data = JSON.parse(data);\n            $( \"#messages\" ).append( \"\u003cp\u003e\"+data.user+\" : \"+data.message+\"\u003c/p\u003e\" );\n        });\n\n        $('input.send').click(function(e){\n            e.preventDefault();\n            search();\n        });\n\n        function search() {\n            var message = $('input.message').val();\n            $.ajax({\n                type: \"POST\",\n                url: \"sendmessage\",\n                data: { \"_token\": $('meta[name=\"csrf-token\"]').attr('content'), \"message\": message},\n                cache: false,\n                success: function(results){\n                }\n            });\n        }\n\n    \u003c/script\u003e\n\n@endsection\n\n\n```\n\n\u003ca name=\"step7\"\u003e\u003c/a\u003e\n\u003ch1\u003eStep 7: Create Server File\u003c/h1\u003e\n\nIn the project root folder create a new file \u003cb\u003eserver.js\u003c/b\u003e file\n\n```javascript\nvar app = require('express')();\nvar server = require('http').Server(app);\nvar io = require('socket.io')(server);\nvar redis = require('redis');\nvar port_number = 8890;\n\nserver.listen(port_number, function(){\n    console.log(\"Listening on \"+port_number)\n});\nio.on('connection', function (socket) {\n\n    console.log(\"new client connected\");\n    var redisClient = redis.createClient();\n    redisClient.subscribe('message');\n\n    redisClient.on(\"message\", function(channel, message) {\n        console.log(\"new message in queue \"+ message + \"channel\");\n        socket.emit(channel, message);\n    });\n\n    socket.on('disconnect', function() {\n        redisClient.quit();\n    });\n});\n\n```\n\n\u003ca name=\"step8\"\u003e\u003c/a\u003e\n\u003ch1\u003eStep 8: Test and Run\u003c/h1\u003e\n\nIn the project root folder create a new file \u003cb\u003eserver.js\u003c/b\u003e file\n\nTo test the application you can start the \u003cb\u003eRedis\u003c/b\u003e and \u003cb\u003eNodeJS\u003c/b\u003e server.\n\nIn terminal run:\n```bash\nredis-server\n```\n\nIn your project root folder run:\n```bash\nnode server.js\n```\nIn your project root folder run: node server.js\n\nLogin into you app and test by sending a message","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmosesesan%2Fmesan-laravel-socketio","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fmosesesan%2Fmesan-laravel-socketio","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmosesesan%2Fmesan-laravel-socketio/lists"}