0

I am working on laravel application using websockets. I have configured websockets from the library

Building a real time application like uber or ola.

Customer are creating a trip with start and end location.

In backend selecting the nearest driver location and need to broadcast trip to nearest drivers

Event is broadcasted when new trip has been created.

EventServiceProvider

\App\Events\NewTripHasCreatedEvent::class => [
        \App\Listeners\SendTripCreationNotificationToTheDriverListener::class,
    ],

NewTripHasCreatedEvent

class NewTripHasCreatedEvent
{
    use Dispatchable, InteractsWithSockets, SerializesModels;

    public $trip;
    public $trip_details;

    /**
     * Create a new event instance.
     *
     * @return void
     */
    public function __construct(Trip $trip, $trip_details)
    {
        $this->trip = $trip;
        $this->trip_details = $trip_details;
    }

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

SendTripCreationNotificationToTheDriverListener

public function handle(NewTripHasCreatedEvent $event)
{
     Find nearest driver
     $km = 0.008997742; //1 km = 0.008997742 degree
    $drivers_distance = 5;
    $query      = Driver::Distance('location', $trip->from_location, $drivers_distance * $km)->take(5)->pluck('user_id');
    //Here send notification to Driver
}
B L Praveen
  • 1,812
  • 4
  • 35
  • 60

1 Answers1

0

in order to send a message to a specific client with laravel websockets they need to be subscribed to a channel by themselves, there is no way to specify a single client to send to.

i would suggest switching to node ws for your backend, laravel-websockets isn't designed for this. (i was facing the exact same issue, was half way through building server in laravel and switched to node, it was instantly LOADS easier)

if you absolutely need to stick with laravel-websockets then you can use this workaround

  1. broadcast a message to everyone with the id of the user/s you want to send a private message to, and a random string of chars
  2. the clients check if the id matches theirs, if they do, they take the random chars and subscribe to the channel
  3. server broadcasts the private message to the new channel which only the newly subscribed user/s recieve.
  4. client/s unsubscribe from the new channel.

if you do switch to node then you can send a message to a specific client very easily

aidan byrne
  • 524
  • 1
  • 5
  • 11