Is it possible emit data to channel in laravel echo?

Viewed 2061

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!

3 Answers

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});
});

By default, Echo will use the /broadcasting/auth endpoint to authorize channel access. If your client side is not on the same host you will have to customize the authEndpoint of pusher. You may specify your own authorization endpoint by passing the authEndpoint configuration option to your Echo instance:

window.Echo = new Echo({
    broadcaster: 'pusher',
    key: 'your-pusher-channels-key',
    authEndpoint: '/custom/endpoint/auth', //customize here.
});

Add this to your Event (App\EventName):

public function broadcastWith()
{
    return [
        'data' => "your data",
        'moredata' => "more data",
    ];
}

And access your data like this in JS:

Echo.channel('channel-name')
    .listen('EventName', (event) => {
        console.log(event.data);
        console.log(event.moredata);
        console.log(event['moredata']);
    }
Related