Search code examples
phplaravelsocketssocket.iolaravel-echo

Is it possible emit data to channel in laravel echo?


I have two separate laravel project and installed on one of these project laravel-echo and on another one laravel-echo-server.

I connected this project together and transfer data from server to client but I can't emit data from client to server.

event in server:

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

    public $prices;

    /**
     * Create a new event instance.
     *
     * @param int[] $prices
     */
    public function __construct($prices = ['a' => 11000, 'b' => 420])
    {
        $this->prices = $prices;
    }

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

    public function broadcastAs()
    {
        return 'financial.prices';
    }
}

rotue in server:

Route::get('/fire', function () {

    $prices = [
        'a' => rand(11000, 120000),
        'b' => rand(450, 5000)
    ];
    event(new \App\Events\TestEvent($prices));
    return 'done';
});

client:

import Echo from 'laravel-echo';

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

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

window.Echo.logToConsole = true;

window.Echo.join('bla-bla')
    .here((data) => {
        console.log('asdasd');
    })
    .joining((data) => {
        console.log('asdasd');
    })
    .leaving((data) => {
        console.log('asdasd');
    });

how can I do this? It would be highly appreciated if anyone can advise me!😊


Solution

  • you need to use emit after connected to the socket server:

    window.io = require('socket.io-client');
    const socket = io('https://localhost:8080');
    
    socket.on('connect', () => {
        socket.emit('your_channel_to_emit', {your_data});
    });