1

I am trying to make a realtime socket.io app.

The redis connect is good,because I can do this in tinker and it works fine.

Redis::publish('test-channel','test-message');

but I want to use event to publish the message

app\Events\ChatMessage.php:

    namespace App\Events;

    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;

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

        public $name;
        public $message;

        public function __construct($name,$message)
        {

          $this->name = $name;
          $this->message = $message;
        }

        public function broadcastOn()
        {

          return ['test-channel'];
          // return new Channel('test-channel');
        }
    }

in public function broadcastOn

i tried

           return ['test-channel'];
           return 'test-channel';
           return new Channel('test-channel');

all doesn't work.

i do this in tinker

event(new App\Events\ChatMessage('bear','banana'));

and laravel just return []

I know I can use listener to handle it with Redis::publish(), but most of tutorial doesn't do it.

what else do I have to check?

0

1 Answer 1

3

I found that even I fire the event, the message will be queued.

After I run

php artisan queue:listen

the client recive the message!

So I solve it by changing ShouldBroadcast to ShouldBroadcastNow, and it work!

Sign up to request clarification or add additional context in comments.

2 Comments

I guess it's the problem of laravel version, mine is 5.6 now.
I just have this problem now, I'm using the latest version of Laravel 7. And I could only solve the problem with ShouldBroadcastNow. I'm using dokku on the production server. Locally everything works fine with ShouldBroadcast

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.