0

I'm using Laravel for backend and React Native for front end, I'm using Laravel Websockets to handle real time functionality

https://beyondco.de/docs/laravel-websockets/getting-started/introduction

I have this function on backend which dispatches an event:

    public function store(Request $request)
    {
        try{
            $validator= Validator::make($request->all(), [
                'origin' => 'required',
                'originName'=>'required',
                'comments'
             ]);
     
             
             if($validator->fails()){
                 return $validator->errors();
             }
     
             $trip= $request->user()->trips()->create($request->only([
                'origin',
                'originName',
                'comments',
             ]));
            EventCreated::dispatch($trip, $request->user());
            return $trip;
        } catch(\Exception $e){
            return response()->json(['error'=> $e->getMessage()], 400);
        }
        }

` The Event:

<?php

namespace App\Events;

use App\Models\Trip;
use App\Models\User;
use Illuminate\Broadcasting\Channel;
use Illuminate\Queue\SerializesModels;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Broadcasting\PresenceChannel;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
use Illuminate\Contracts\Broadcasting\ShouldBroadcastNow;

class EventCreated implements ShouldBroadcast
{
    use Dispatchable, InteractsWithSockets, SerializesModels;

    public $trip;
    private $user;
    /**
     * Create a new event instance.
     */
    public function __construct(Trip $trip, User $user)
    {
        $this->trip = $trip;
        $this->user = $user;
    }

    /**
     * Get the channels the event should broadcast on.
     *
     * @return array<int, \Illuminate\Broadcasting\Channel>
     */
    /**
 * The name of the queue connection to use when broadcasting the event.
 *
 * @var string
 */
//public $connection = 'pusher';
 
/**
 * The name of the queue on which to place the broadcasting job.
 *
 * @var string
 */
public $queue = 'default';

    public function broadcastOn(): array
    {
        return [
            new Channel('drivers')
        ];
    }
}

Here's the react native part:

 ...<Button title="Button" onPress={getPusher} ></Button>...

   const pusher = Pusher.getInstance();

    const onEvent = (event: PusherEvent)=>{
      console.log(`onEvent> ${event}`)
    }

    const onSubscriptionSucceeded = (channelName) => {
      console.log(channelName)
      console.log(
        `onSubscriptionSucceeded: ${channelName} data: ${JSON.stringify(data)}`
      );
      const channel= pusher.getChannel(channelName);
  
      if (!channel) {
       console.log("No Channel");
       return
      }
      const me = channel.me;
    //  onChangeMembers([...channel.members.values()]);
      console.log(me);
    }
        
    const onError = (message, code, error) => {
      console.log(`onError: ${message} code: ${code} exception: ${error}`);
    };


    const onSubscriptionError = (
      channelName,
      message,
      e
    ) => {
      log(`onSubscriptionError: ${message}, channelName: ${channelName} e: ${e}`);
    };
  
    const onDecryptionFailure = (eventName, reason) => {
      log(`onDecryptionFailure: ${eventName} reason: ${reason}`);
    };
  

    const onConnectionStateChange = (
      currentState,
      previousState
    ) => {
      console.log(
        `onConnectionStateChange. previousState=${previousState} newState=${currentState}`
      );
    };
    const getPusher = async()=>{
      try{
        await pusher.init({
          apiKey: APP_KEY,
          cluster: APP_CLUSTER,
          authEndpoint: "http://127.0.0.1:8000/pusher/broadcasting/auth",
          port: 6001,
          onConnectionStateChange,
          onError,
          onEvent,
          onSubscriptionSucceeded,
          onSubscriptionError,
          onDecryptionFailure
        }).catch(error=>console.log(error));
        
   
  
    
      await pusher.subscribe({channelName:'drivers',
    //  onEvent,
    //  onSubscriptionSucceeded
    });
      await pusher.connect();
       console.log(pusher)
      } catch(e){
        console.log(`ERROR> ${e}`)
      }
    }

When I press the button, it successfully subscribes to the "drivers" channel and fetches the data on the queue, however, when sending dispatching the laravel event in PostMan, it doesn't send anything to the "onEvent" function, almost like it didn't exist, please help.

I've tried using both ShouldBroadcast and ShouldBroadcastNow, neither of them display data in React Native

The only difference is the former saves data in the queue which is not visible except when first subscribing to the "drivers" channel in pusher-websocket-react-native, and the latter is visible everywhere in the localhost:8000/laravel-websockets server as well as console.log when subscribing to the channel.

I've tried to read the documentation, but nothing shows up that would help me with onEvent not logging the data being updated after the dispatch.

  • Do you see any events on Pusher's debug console? – Salman Malik Aug 11 '23 at 23:33
  • No, I'm dispatching the event from Postamn and on Pusher's debug console it doesn't return anything, it does on PHP terminal and http://localhost:8000/laravel-websockets, however. – John Smith Aug 13 '23 at 16:25
  • I'm sorry to say that, your code have a lot of problems and needs improvement before it could be answered. It is obvious that you have not followed the docs properly. Your event is totally wrong. There is no channel name defined related to event so it will simply get lost after being fired, your event is not following the format as specified by Pusher, you are listening to the event the wrong way. I recommend following this series by [Scalable Scripts](https://www.youtube.com/watch?v=bm5XPlWW1EA&ab_channel=ScalableScripts) to learn Pusher using any technology you are comfortable with. – Salman Malik Aug 13 '23 at 20:57
  • Will follow that, but I did follow the documentation properly, I double checked the data on the .env file, I did define the channel name, it's called "drivers", and it's on the Event code I showed at the start, also I'm following the exact same format, maybe without "broadcastAs" and maybe I dispatched the event in a different (but still valid) way, how is that totally wrong? – John Smith Aug 14 '23 at 12:40
  • I even tried adding "broadcastAs" and changed the way the event is dispatched ( event(new TripCreated($trip, $request->user()));) and it still doesn't send message to Pusher. I want to make clear I'm using Laravel-Websockets. – John Smith Aug 14 '23 at 13:07

0 Answers0