skip to Main Content

I am following the tutorial given in https://medium.com/@dennissmink/laravel-echo-server-how-to-24d5778ece8b .

I installed laravel-echo-server, redis, socket.io, laravel-echo.

This is the configuration of laravel-echo-server init

{
    "authHost": "http://localhost",
    "authEndpoint": "/broadcasting/auth",
    "clients": [],
    "database": "redis",
    "databaseConfig": {
        "redis": {},
        "sqlite": {
            "databasePath": "/database/laravel-echo-server.sqlite"
        }
    },
    "devMode": true,
    "host": null,
    "port": "6001",
    "protocol": "http",
    "socketio": {},
    "secureOptions": 67108864,
    "sslCertPath": "",
    "sslKeyPath": "",
    "sslCertChainPath": "",
    "sslPassphrase": "",
    "subscribers": {
        "http": true,
        "redis": true
    },
    "apiOriginAllow": {
        "allowCors": false,
        "allowOrigin": "",
        "allowMethods": "",
        "allowHeaders": ""
    }
}

This js code is at the bottom of app.blade.php which is included in all pages

<script type="module">
    import Echo from 'laravel-echo'

    window.io = require('socket.io-client');window.Echo = new Echo({
        broadcaster: 'socket.io',
        host: window.location.hostname + ':6001'
    });

    window.Echo.channel('test-event')
        .listen('ExampleEvent', (e) => {
            console.log(e);
        });
</script>

I created an event php artisan make:event ExampleEvent as follows

namespace AppEvents;

use IlluminateBroadcastingChannel;
use IlluminateBroadcastingInteractsWithSockets;
use IlluminateBroadcastingPresenceChannel;
use IlluminateBroadcastingPrivateChannel;
use IlluminateContractsBroadcastingShouldBroadcast;
use IlluminateFoundationEventsDispatchable;
use IlluminateQueueSerializesModels;

class ExampleEvent implements ShouldBroadcast
{
    use Dispatchable, InteractsWithSockets, SerializesModels;

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

    /**
     * Get the channels the event should broadcast on.
     *
     * @return IlluminateBroadcastingChannel|array
     */
    public function broadcastOn()
    {
        return new Channel('test-event');
    }

    public function broadcastWith()
    {
        return [
            'data' => 'Hi bro!'
        ];
    }
}

and the following route

Route::get('test-broadcast', function(){
    broadcast(new AppEventsExampleEvent);
});

I also started a queue listener

php artisan queue:listen --tries=1

When I visit the page test-broadcast I see this in terminal

enter image description here

But the console of the browser shows nothing while the console.log(e); must return something. I also did this

    window.Echo.channel('test-event')
        .listen('ExampleEvent', (e) => {
            alert('hi')
            console.log(e);
        });

but nothing was alerted. It seems something is wrong with listening.

Thanks in advance.

update

I receive this error from console of browser when visiting login or any page includes app.blade.php

enter image description here

Update

I updated the script codes as below

    <script src="http://{{ Request::getHost() }}:6001/socket.io/socket.io.js"></script>
    <script src="{{ asset('/js/app.js') }}"></script>
    <script type="module">
        import Echo from 'laravel-echo'

        window.Echo = new Echo({
         broadcaster: 'socket.io',
         host: window.location.hostname + ':6001'
         });

        window.Echo.channel('test-event')
            .listen('.ExampleEvent', (e) => {
                console.log(e);
            });
    </script>

The console still report error

TypeError: Error resolving module specifier: laravel-echo

update

I run

npm run development -- --watch

and this is the result

cross-env NODE_ENV=development node_modules/webpack/bin/webpack.js –progress –hide-modules –config=node_modules/laravel-mix/setup/webpack.config.js
“–watch”

'cross-env' is not recognized as an internal or external command,
operable program or batch file.
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! @ development: `cross-env NODE_ENV=development node_modules/webpack/bin/webpack.js --progress --hide-modules --config=node_modules/laravel-mix/
setup/webpack.config.js "--watch"`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the @ development script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     C:UsersMamadAppDataRoamingnpm-cache_logs2020-03-05T14_59_30_604Z-debug.log
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! @ watch: `npm run development -- --watch`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the @ watch script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     C:UsersMamadAppDataRoamingnpm-cache_logs2020-03-05T14_59_30_697Z-debug.log

2

Answers


  1. Altogether this what is required:

    1. Default Laravel installation
    2. composer require predis/predis
    3. Installation of NPM modules (laravel-echo-server, socket.io & laravel-echo)
    4. Set up Laravel Echo Server through console (mostly default settings, except for domain name):
      {
      "authHost": "http://echo",
      "authEndpoint": "/broadcasting/auth",
      "clients": [
      {
      "appId": "fc3de97a1787ea04",
      "key": "ecf31edced85073f7dd77de1588db13b"
      }
      ],
      "database": "sqlite",
      "databaseConfig": {
      "redis": {},
      "sqlite": {
      "databasePath": "/database/laravel-echo-server.sqlite"
      }
      },
      "devMode": true,
      "host": null,
      "port": "6001",
      "protocol": "http",
      "socketio": {},
      "secureOptions": 67108864,
      "sslCertPath": "",
      "sslKeyPath": "",
      "sslCertChainPath": "",
      "sslPassphrase": "",
      "subscribers": {
      "http": true,
      "redis": true
      },
      "apiOriginAllow": {
      "allowCors": true,
      "allowOrigin": "http://echo:80",
      "allowMethods": "GET, POST",
      "allowHeaders": "Origin, Content-Type, X-Auth-Token, X-Requested-With, Accept, Authorization, X-CSRF-TOKEN, X-Socket-Id"
      }
      }

    5. Setup of Redis Server and connecting to it with Laravel broadcasting.php file

    'default' => env('BROADCAST_DRIVER', 'redis')

    or BROADCAST_DRIVER=redis in .env file

    1. Adding route in web.php

    Route::get('/test-broadcast', function(){
    broadcast(new AppEventsExampleEvent);
    return response('OK');
    });

    1. Adding code in bootstrap.js:

    import Echo from ‘laravel-echo’

    window.io = require(‘socket.io-client’);
    window.Echo = new Echo({
    broadcaster: ‘socket.io’,
    host: window.location.hostname + ‘:6001’
    });

    ADDED

    window.Echo.channel(‘MyChannel’)
    .listen(‘.ExampleEvent’, (e) => {
    console.log(e);
    });

    1. Running npm run dev to compile all Javascript modules
    2. Running laravel-echo-server start to start Laravel Echo Server
    3. Running php artisan queue:listen --tries=1 to start the listen queue
    4. Accessing the http://echo/test-broadcast

    UPDATED

    11.1 Adjust methods for the ExampleEvent to:

    public function broadcastOn()
    {
    return new Channel(‘MyChannel’);
    }

    public function broadcastAs()
    {
    return ‘ExampleEvent’;
    }

    11.2 In welcome.blade.php, before BODY tag, add

    <script type="text/javascript" src="/js/app.js"></script>

    11.3 in database.php, set redix prefix to empty string value

    'prefix' => env('REDIS_PREFIX', '')

    DO NOT FORGET TO RE-RUN npm run dev and clear browser cache

    Results

    Queue running

    Laravel Echo Server console results

    Client & Server alongside

    Login or Signup to reply.
  2. From your bug, I think your packages are not installed or are imported incorrectly. You can try install package

    npm install --save socket.io-client laravel-echo
    

    Add those code to end of fileresources/js/bootstrap.js

    import Echo from "laravel-echo"
    
    window.io = require('socket.io-client');
    
    window.Echo = new Echo({
        broadcaster: 'socket.io',
        host: window.location.hostname + ':6001'
    });
    

    and run npm run watch

    Reference: https://laravel.com/docs/master/broadcasting#driver-prerequisites part socket.io

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search