kakajansh / echo

Laravel Echo for your Flutter apps.
MIT License
107 stars 68 forks source link

provide backend laravel example #18

Closed mghase closed 4 years ago

mghase commented 4 years ago

i tried to connect with laravel websocket but didnt work

yazanIbrahim commented 4 years ago

@mghase what is your problem exactly ?

danielpenya commented 4 years ago

Same problem. I need a example. Not works.

yazanIbrahim commented 4 years ago

@danielpenya i have followed this tutorial https://www.youtube.com/watch?v=ORga8ZavCc8&list=PLwAKR305CRO9rlj-U9oOi4m2sQaWN6XA8 setting up laravel websocket and integrated with this plugin successfully , just remember when you want to authorise private channel you need to send the the access token from the app in the authorization header, if you faced any problem during setting up you can share your problem here , good luck

Chris1234567899 commented 4 years ago

I had to use another pusher library. With the suggested one I could not make it work either because of some ssl handshake exceptions. Try using https://pub.dev/packages/pusher_dart

I have:

 final pusher = Pusher(
      DotEnv().env['PUSHER_APP_KEY'],
      PusherOptions(
        host: DotEnv().env['PUSHER_HOST'],
        port: int.parse(DotEnv().env['PUSHER_PORT']),
        authEndpoint: DotEnv().env['API_URL'] + "/broadcasting/auth",
        auth: PusherAuth(headers: {
          'Authorization': 'Bearer $token',
          'Content-Type': 'application/json',
          'Accept': 'application/json'
        }),
      ),
    );

    Echo echo = new Echo({
      'broadcaster': 'pusher',
      'client': pusher,
      'auth': {
        'endPoint': DotEnv().env['API_URL'] + "/broadcasting/auth",
        'headers': {
          'Authorization': 'Bearer $token',
          'Content-Type': 'application/json',
          'Accept': 'application/json'
        }
      }
    });

    echo
        .channel(
            'private-channel.' + id.toString())
        .listen('MessageEvent', (e) {
             print(e.toString();)
     });

Note that I had to add a custom host and port to the library: https://github.com/jaysson/pusher_dart/pull/3 https://github.com/Chris1234567899/pusher_dart

Furthermore, something that is not very clear is the naming convention of the channel. In echo you have to name your channel like: private-my-channel.someId (notice the point! before id, it must be a point, not some other character and you must include an id wildcard apparently). in laravel however, the private- gets erased, so in routes/channels.php put

Broadcast::channel('my-channel.{id}', function ($user, $id) {
    return true; //your logic
});

and to broadcast your event, use App/Events/MyEvent.php:

public function broadcastOn()
    {
        return new PrivateChannel('my-channel.'.$this->message->id);
    }

Notice to not put "private-" before the channel name in both cases in laravel, it get's removed by laravel.