Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Inlogic's avatar

Laravel reverb

how to use laravel reverb as a standalone websocket server without having to use laravel echo that is using laravel reverb as standalone websocket server that i can use any js library to connect to it or connect to the websocket via a flutter mobile app

0 likes
7 replies
Inlogic's avatar

yes i did try to connect it while sniffing the laravel echo implementation i was able to grab the url to use to connect to it and it worked but sending message from the socket itself is what i couldnt figure out how to receive the message in laravel

kamil-kmetyk's avatar

I think I found solution how connection between Flutter and Laravel Reverb might be achieved. Found an atricle on Medium (which I can't link here because my account's here too fresh 😅)

In shorthand in your app.php:

  1. remove channels __DIR__.'/../routes/channels.php',
  2. and place it withBroadcasting method.
  3. don't forget about middlewares
  4. add BROADCAST_CONNECTION=reverb to your .env
  5. do not forget about php artisan optimize

Example:

return Application::configure(basePath: dirname(__DIR__))
    ->withProviders()
    ->withRouting(
        web: __DIR__.'/../routes/web.php',
        api: __DIR__.'/../routes/api.php',
        commands: __DIR__.'/../routes/console.php',
        health: '/up',
        apiPrefix: 'api/v1',
    )
    ->withBroadcasting(
        channels: __DIR__.'/../routes/channels.php',
        attributes: ['prefix' => 'api', 'middleware' => ['auth:sanctum']],
    )
1 like
sarmaRandeepGithub12345's avatar

@kamil-kmetyk hi I am using dart pusher channels on the frontend : Future dartconnect() async { try { final auth = Provider.of<AuthState>(context, listen: false);

  const hostOptions = PusherChannelsOptions.fromHost(
    scheme: 'ws',
    host: '223.238.102.62',
    key: 'mmh5zmnirsuvmwhr6swm',
    shouldSupplyMetadataQueries: true,
    metadata: PusherChannelsOptionsMetadata.byDefault(),
    port: 8080,
  );

  final client = PusherChannelsClient.websocket(
      options: hostOptions,
      connectionErrorHandler: (exception, trace, refresh) {
        refresh();
      });

  // final channel = client.publicChannel(
  //   'test',
  // );
  // print("token is private-chat.${auth.user!.id}");
  final private = client.privateChannel(
    'chat.${auth.user!.id}',
    authorizationDelegate:
        EndpointAuthorizableChannelTokenAuthorizationDelegate
            .forPrivateChannel(
      authorizationEndpoint: Uri.parse('$domain/api/broadcasting/auth'),
      headers: {
        'Authorization': 'Bearer ${auth.loginToken}',
      },
    ),
  );

  // StreamSubscription<ChannelReadEvent> channelSubscription =
  //     channel.bind('App\\Events\\MessageSent').listen((event) {
  //   print('Event received: ${event.data}');
  // });

  StreamSubscription<ChannelReadEvent> privateSubscription =
      private.bind('message.sent').listen((event) {
    print('Private event received:${event.data} ');
  });

  client.onConnectionEstablished.listen((s) {
    print('Connection established');
    // channel.subscribe();
    private.subscribe();
  });

  print("just before request");
  await client.connect();
  print("just after request");
} catch (e) {
  print("Datetime ${DateTime.now()} error $e");
}

} made an event in backend:class MessageSent implements ShouldBroadcastNow { use Dispatchable, InteractsWithSockets, SerializesModels;

/**
 * Create a new event instance.
 */
public $message;
public function __construct(Messages $message)
{
    $this->message = $message;
}

/**
 * Get the channels the event should broadcast on.
 *
 * @return array<int, \Illuminate\Broadcasting\Channel>
 */
public function broadcastOn(): array
{
    $channels = [];

    $participants = ChatParticipants::where('chat_id', $this->message->chat_id)->pluck('user_id');

    foreach ($participants as $userId) {
        $channels[] = new PrivateChannel('chat.' . $userId);
    }
    return $channels;

    // return [
    //     new Channel('test'),
    //     new PrivateChannel('chat.' . $this->message->sender_id)

    // ];
}
public function broadcastAs(): string
{
    return 'message.sent';
}

} ..updated the bootstrap/app.php and broadcased message but still not working

Inlogic's avatar

i endup using laravel-swoole because i just need a standalone websocket server without being force into a particular protocol and be connected using any tool

Please or to participate in this conversation.