I am Trying to make a ChatApp using Flutter’s dart_pusher_channels and Laravel Reverb. AS given in Laravel docs I have setup Sanctum authentication. Then created an Event in Laravel:
class MessageSent implements ShouldBroadcast
{
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, IlluminateBroadcastingChannel>
*/
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;
}
public function broadcastAs(): string
{
return 'message.sent';
}
}
Then I have updated the routes/channels.php:
Broadcast::channel('chat.{id}', function (User $user, $id) {
return $user->id === $id;
});
I have also tried with ShouldBroadcastNow…Next I have made changes in bootstrap/app.php
return Application::configure(basePath: dirname(__DIR__))
->withRouting(
web: __DIR__.'/../routes/web.php',
api: __DIR__.'/../routes/api.php',
commands: __DIR__.'/../routes/console.php',
// channels: __DIR__.'/../routes/channels.php',
health: '/up',
)
->withBroadcasting(
channels: __DIR__.'/../routes/channels.php',
attributes: ['prefix' => 'api', 'middleware' => ['auth:sanctum']],
)
->withMiddleware(function (Middleware $middleware) {
//
})
->withExceptions(function (Exceptions $exceptions) {
//
})->create();
then after message is created in the db I have tried to broadcast the message :
broadcast(new MessageSent($message));
Then I ran my backend server on port 8000,also my reverb server using ‘php artisan reverb:start –debug’ on port 8080 and also ‘php artisan queue:list’.Now in flutter I have used this snippet to connect to server :
Future<void> dartconnect() async {
try {
final auth = Provider.of<AuthState>(context, listen: false);
const hostOptions = PusherChannelsOptions.fromHost(
scheme: 'ws',
host: '*.*.*.*',
key: 'reverb_key',
shouldSupplyMetadataQueries: true,
metadata: PusherChannelsOptionsMetadata.byDefault(),
port: 8080,
);
final client = PusherChannelsClient.websocket(
options: hostOptions,
connectionErrorHandler: (exception, trace, refresh) {
refresh();
});
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> privateSubscription =
private.bind('message.sent').listen((event) {
print('Private event received:${event.data} ');
});
client.onConnectionEstablished.listen((s) {
print('Connection established');
private.subscribe();
});
await client.connect();
} catch (e) {
}
}
I am not able to get response in my frontend. I have tried other drivers like pusher as well and used other flutter packages like Web socket channel, pusher channels fixed, etc. But none seems to work
2
Answers
create a
in your php event file, It is best to hook the broadcast event to a parent model id of the ChatParticipants,in this case Chat model.
routes/channels.php:
make sure to add ‘X-Socket-ID’: socketId.value to your headers when submiting data to your server.
in CommentsController file
// in CommentCreatedEvent file
in channels.php file
in hostel_socket.dart file
in hostelController.dart file