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

如何在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) => { }  
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 vb net 使用 sendMessage 如何输入鼠标坐标
  • ¥200 求能开发抖音自动回复卡片的软件
  • ¥15 关于freesurfer使用freeview可视化的问题
  • ¥100 谁能在荣耀自带系统MagicOS版本下,隐藏手机桌面图标?
  • ¥15 求SC-LIWC词典!
  • ¥20 有关esp8266连接阿里云
  • ¥15 C# 调用Bartender打印机打印
  • ¥15 我这个代码哪里有问题 acm 平台上显示错误 90%,我自己运行好像没什么问题
  • ¥50 C#编程中使用printDocument类实现文字排版打印问题
  • ¥15 找会编程的帅哥美女 可以用MATLAB里面的simulink编程,用Keil5编也可以。