从Laravel广播中的多个专用频道发送通知

时间:2020-05-10 12:52:59

标签: php laravel broadcast pusher laravel-echo

我将pusherLaravel BroadcastingLaravel Echo配置为向用户发送通知。对于单个私人频道来说,它工作正常。

我有两个私人频道。

  1. App.User {id}
  2. YouthAdd.YouthAdd {id}

但是通知仅通过App.User{id}频道传递

我如何也可以从其他渠道发送通知?

我的用户类别

namespace App;

use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;

class User extends Authenticatable
{
    use Notifiable;

    /**
     * The channels the user receives notification broadcasts on.
     *
     * @return string
     */
    public function receivesBroadcastNotificationsOn()
    {
        return 'App.User.'.$this->id;
        return 'YouthAdd.YouthAdd.'.$this->id;
    }
}

我的Channels.php路由文件

Broadcast::channel('App.User.{id}', function ($user, $id) {
    return (int) $user->id === (int) $id;
});

Broadcast::channel('YouthAdd.YouthAdd.{id}', function ($user, $id) {
    return (int) $user->id === (int) $id;
});

我的前端

<script>
  var userId = $('meta[name="userId"]').attr('content');
    Echo.private('App.User.' + userId)
    .notification((notification) => {
        toastr.warning(notification.title, notification.name, {closeButton: true, timeOut: 5000000});
    });


      Echo.private('YouthAdd.YouthAdd.' + userId)
      .notification((notification) => {
          console.log(notification.youth);
          toastr.error(notification.youth.name, notification.youth.nic, {closeButton: true, timeOut: 5000000});
      });

    </script>

任何人都可以回答这个问题吗?

2 个答案:

答案 0 :(得分:1)

而不是:

public function receivesBroadcastNotificationsOn()
{
    return 'App.User.'.$this->id;
    return 'YouthAdd.YouthAdd.'.$this->id;
}

尝试一下:

public function receivesBroadcastNotificationsOn()
{
     return [
        'App.User.'.$this->id,
        'YouthAdd.YouthAdd.'.$this->id
    ];
}

答案 1 :(得分:0)

尝试一下:

        $channelNames = ['App.User.' . $this->id, 'YouthAdd.YouthAdd.'.$this->id];
        $channels = [];
        foreach ($channelNames as $channel) {
            $channels[] = new PrivateChannel($channel);
        }

        return $channels;