laravel Event shouldbroadcast not working

I am trying to make a realtime app.

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


but I want to use event to publish the message


    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?

1 answer

  • answered 2018-07-11 06:07 黃皓哲

    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!