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 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法
  • ¥15 可否在不同线程中调用封装数据库操作的类
  • ¥15 微带串馈天线阵列每个阵元宽度计算
  • ¥15 keil的map文件中Image component sizes各项意思