Skip to content

Instantly share code, notes, and snippets.

@brainlagid
Last active September 30, 2024 22:32
Show Gist options
  • Save brainlagid/15666f13c5b27c4f8f5702559473c240 to your computer and use it in GitHub Desktop.
Save brainlagid/15666f13c5b27c4f8f5702559473c240 to your computer and use it in GitHub Desktop.
Setup Laravel with Socket.io [Ubuntu 20.04]

Server Requirement

  • Redis sudo apt install redis-server
  • Composer here
  • npm sudo apt install nodejs npm
  • laravel-echo-server npm install -g laravel-echo-server

Laravel Dependencies Requirement

  • predis
  • laravel-echo
  • socket.io-client ^2.4.0 issue

Installation

  • Install fresh laravel via Composer laravel new laravel-socket-io
  • Go to Laravel directory cd laravel-socket-io
  • Add predis composer require predis/predis
  • Add laravel-echo and socket.io client npm install --save laravel-echo socket.io-client@2.4.0
  • Create laravel-echo-server configuration laravel-echo-server init
  • Specify .env
...
# Broadcast
BROADCAST_DRIVER=redis
...
# Redis
REDIS_HOST=127.0.0.1
REDIS_PASSWORD=null
REDIS_PORT=6379
REDIS_CLIENT=predis
REDIS_PREFIX=""
...
# Laravel Echo Server
LARAVEL_ECHO_SERVER_REDIS_HOST=127.0.0.1
LARAVEL_ECHO_SERVER_REDIS_PORT=6379
LARAVEL_ECHO_SERVER_REDIS_PASSWORD=null
  • Create new file resources/js/echo.js
# echo.js
import Echo from 'laravel-echo';

window.io = require('socket.io-client');

window.Echo = new Echo({
    broadcaster: 'socket.io',
    host: window.location.hostname + ':6001'
});
  • Add require('./echo.js'); at bottom of file resources/js/app.js
  • Run npm install
  • Run npm run dev
  • Enable channel route, Uncomment App\Providers\BroadcastServiceProvider::class,
  • Add route routes/channels.php
...
Broadcast::channel('EveryoneChannel', function () {
    return true;
});
...
  • Create new event php artisan make:event EveryoneEvent and edit
<?php

namespace App\Events;

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

class EveryoneEvent implements ShouldBroadcast
{
    use Dispatchable, InteractsWithSockets, SerializesModels;
    
    /**
    * The name of the queue connection to use when broadcasting the event.
    *
    * @var string
    */
    public $connection = 'redis';

    /**
    * The name of the queue on which to place the broadcasting job.
    *
    * @var string
    */
    public $queue = 'default';

    /**
     * Create a new event instance.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Get the channels the event should broadcast on.
     *
     * @return \Illuminate\Broadcasting\Channel|array
     */
    public function broadcastOn()
    {
        return new Channel('EveryoneChannel');
    }

    /*
     * The Event's broadcast name.
     * 
     * @return string
     */
    public function broadcastAs()
    {
        return 'EveryoneMessage';
    }
    
    /*
     * Get the data to broadcast.
     *
     * @return array
     */
    public function broadcastWith()
    {
        return [
            'message'=> 'Hello!'
        ];
    }
}
  • Add route for send and receiver broadcast at file routes/web.php
...
Route::get('/send', function () {
    broadcast(new App\Events\EveryoneEvent());
    return response('Sent');
});

Route::get('/receiver', function () {
    return view('receiver');
});
...
  • Create new view resources/views/receiver.blade.php
<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">

        <title>Receiver</title>

        <script type="application/javascript" src="{{ asset('js/app.js') }}"></script>
    </head>
    <body>
        <div id="messages"></div>
        <script
            src="https://code.jquery.com/jquery-2.2.4.js"
            integrity="sha256-iT6Q9iMJYuQiMWNd9lDyBUStIq/8PuOW33aOqmvFpqI="
            crossorigin="anonymous"></script>
        <script type="text/javascript">
           window.Echo.channel('EveryoneChannel')
               .listen('.EveryoneMessage', function (e) {
                   $('#messages').append('<p>' + e.message + '</p>');
                })
        </script>
    </body>
</html>
  • Start laravel-echo-server laravel-echo-server start
  • Start Laravel queue php artisan queue:listen redis --queue=default
  • Start Laravel app php artisan serve
  • Open URL two tabs/browsers
    1. http://localhost:8000/send
    2. http://localhost:8000/receiver
  • When you hit first URL you will see Hello! from second URL.
  • DONE, have a good day!
@SaadLaravelDeveloper
Copy link

Alif

@illusi03
Copy link

Makasih banyakk gan, semoga ilmunya semakin bertambah dan berkah

@brainlagid
Copy link
Author

@illusi03 sama sama gan.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment