duanfu3634 2019-03-27 01:49
浏览 63
已采纳

如何在Laravel中将数据传递给broadcastAs事件方法?

I'm trying to pass data to the method broadcastAs, but I keep getting the error Too few arguments to function App\Events\NotifyUser::broadcastAs(). Below is what I have tried.

I'm calling the event on the Controller this way:

event(new NotifyUser('8', 'banned'));

And I'm trying to access the data on the event this way:

public $user;

public $msg;

public function __construct($user, $msg)
{
    $this->user = $user; //8
    $this->msg = $msg; //banned
}

public function broadcastAs($user)
{
    return "user-logged-$user";
}

It works just fine without the $user variable in the broadcastAs.

  • 写回答

1条回答 默认 最新

  • dscss8996 2019-03-27 01:51
    关注

    You should use it with your set property ($this->user) rather than an argument.

    public $user;
    
    public $msg;
    
    public function __construct($user, $msg)
    {
        $this->user = $user;
        $this->msg = $msg;
    }
    
    public function broadcastAs()
    {
        return "user-logged-" . $this->user->id;
    }
    

    However, are you sure you want to use this there?

     window.Echo.private('channel-name.' + user_id)
            .listen('BroadcastClassName', (e) => { }  
            // you'll edit listen() with broadcastAs
    

    public function broadcastOn()
    {
        return new PrivateChannel('user.'.$this->user->id);
    }
    
    // broadcastAs() is optional
    public function broadcastAs() {
        return 'customEventName';
    }
    

    broadcastAs() is optional for overriding event's name, as default one is class's name itself.

    With my last chunk, this is what you'll get.

     window.Echo.private('user.' + user_id)
            .listen('customEventName', (e) => { }  
    

    If you don't have broadcastAs() at all, in your case, your event name will be "NotifyUser", which seems right to me.

        window.Echo.private('user.' + user_id)
            .listen('NotifyUser', (e) => { }  
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog