I am doing a notification tracking by following a simple example from the internet. Unfortunately, so far, I've managed to make it work for only one user. When I open two users, the message from A to B works, but from B to A does not work. Can someone help me?
channels.php
Broadcast::channel('App.User.{id}', function ($user, $id) {
return (int) $user->id === (int) $id;
});
bootstrap.js
window.Pusher = require('pusher-js');
import Echo from "laravel-echo";
window.Echo = new Echo({
broadcaster: 'pusher',
key: 'some-key',
cluster: 'mt1',
forceTLS: true
});
global.js
var urlChannel = 'App.User.' + $('#user_logado_id').val();
window.Echo.private(urlChannel)
.notification((notification) => {
addNotificacao(notification);
});
Send notification to user.
$user->notify(new NotificacaoPadrao($param));
I would like notifications to be sent to all users.
You can pass both sender and receiver user_id
. So in your channels.php
:
Broadcast::channel('App.User.{from_user_id}.{to_user_id}', function ($user, $from_user_id, $to_user_id) {
return (int) $user->id === (int) $from_user_id || (int) $user->id === (int) $to_user_id;
});
When doing this, you should remember that both user must call the same channel name. E.g. If you have user 1
and 2
sending messages to each other the URL channel of both should be 'App.User.1.2' and NOT 'App.User.2.1'.
Actually there are many ways to do this, one solution is what I mentioned above, but this only works on 1-1 messaging, NOT group message. When you want to send a group message you should create 2 tables: channels
(id, name) and channel_users
(id, channel_id, user_id). And your broadcasts channel route will be like this:
Broadcast::channel('App.User.{channel_id}', function ($user, $channel_id) {
return ChannelUser::where('channel_id', $channel_id)->where('user_id', $user->id)->exists();
});