Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

ahoi's avatar
Level 5

Broadcasting to all recipients of a message

Hello everybody,

I am a little stuck at the moment. So I really hope you can help me out :-)

I am building a little private message system for my Laravel app.

I would like to notify my users on the Event MessageCreated.

This is my event:

<?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;
use Cmgmyr\Messenger\Models\Message;

class MessageCreated implements ShouldBroadcast
{
    use Dispatchable, InteractsWithSockets, SerializesModels;
    
    public $message;
    
    /**
     * MessageCreated constructor.
     *
     * @param \App\Message $message
     */
    public function __construct(Message $message)
    {
        $this->message = $message;
    }
    
    /**
     * Get the channels the event should broadcast on.
     *
     * @return \Illuminate\Broadcasting\Channel|array
     */
    public function broadcastOn()
    {
        return new PrivateChannel('conversation.'.$this->message->user_id);
    }
}

This is my notification:

<?php

namespace App\Notifications;

use Illuminate\Bus\Queueable;
use Illuminate\Notifications\Notification;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Notifications\Messages\BroadcastMessage;
use Illuminate\Support\Facades\URL;
use Illuminate\Support\Facades\Lang;

class MessageCreated extends Notification
{
    use Queueable;
    
    protected $message;
    
    /**
     * Create a new notification instance.
     *
     * @return void
     */
    public function __construct($message)
    {
        $this->message = $message;
    }
    
    /**
     * Get the notification's delivery channels.
     *
     * @param  mixed $notifiable
     *
     * @return array
     */
    public function via($notifiable)
    {
        return ['mail'];
    }
    
    /**
     * Get the mail representation of the notification.
     *
     * @param  mixed $notifiable
     *
     * @return \Illuminate\Notifications\Messages\MailMessage
     */
    public function toMail($notifiable)
    {
        
        return (new MailMessage)->subject('...'));
    }
    
    /**
     * Get the array representation of the notification.
     *
     * @param  mixed $notifiable
     *
     * @return array
     */
    public function toArray($notifiable)
    {
        return [//
        ];
    }
}

This is my event subscriber

<?php

namespace App\Listeners;

use App\Message;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use App\Events\MessageCreated;
use Cmgmyr\Messenger\Models\Thread;
use Illuminate\Support\Facades\Auth;
use App\Notifications\MessageCreated as MessageCreatedNotification;
use App\User;

class MessageEventSubscriber
{
    
    /**
     * MessageEventSubscriber constructor.
     */
    public function __construct()
    {
        //
    }
    
    /**
     * @param \App\Events\MessageCreated $event
     */
    public function handle(MessageCreated $event)
    {
        $participants = Thread::findOrFail($event->message->thread_id)
            ->participantsUserIds();
    
        
        foreach ($participants as $participant) {
            if ($participant != $event->message->user_id) {
                $user = User::findOrFail($participant);
                $user->notify(new MessageCreatedNotification($event->message));
            }
        }
    }
}

I am also working with Laravel Echo:

window.Echo = new Echo({
    broadcaster: 'socket.io',
    host: window.location.hostname + ':6001'
});

window.Echo.private('conversation.'+App.user)
.listen('MessageCreated', (e) => {
    console.log(e);
});

Well - the Mails are being sent without problems. But now I'm a bit stuck on how to send a broadcast message to all the users in the recipients list. And of course I need to do this the most secure way.

I read the Laravel docs the whole day, but unfortunately I did not get a correct solution yet.

Your help is highly appreciated!

0 likes
1 reply
grenadecx's avatar
Level 7

I did something like you a while back, but I used the

broadcast(new \App\Events\MessageCreated($message))->toOthers();

To send the message to all the other users.

But my MessageCreated event isn't the same as yours. I've created a privatechannel for the entire thread and uses that on the broadcastOn

    public function broadcastOn()
    {
        return new PrivateChannel('chat.'.$this->message->thread_id);
    }

That way, all users for that thread joins the same broadcast channel it's easy to use the

broadcast(new \App\Events\MessageCreated($message))->toOthers();

To broadcast the message to all other users in that thread.

And then I deal with security of that channel in the route file to make sure only participants can join the broadcasting channel.

Also, in your case, you could use the notification you use to send the mail to also send the broadcasting event if you wanted to. Then it could be picked up from the laravel echo for notifications.

Echo.private('App.User.' + userId)
    .notification((notification) => {
        console.log(notification.type);
    });

Read more about it over here: https://laravel.com/docs/5.7/notifications#broadcast-notifications

1 like

Please or to participate in this conversation.