【问题标题】:Broadcast::channel callback function is not calledBroadcast::channel回调函数没有被调用
【发布时间】:2020-04-08 08:30:43
【问题描述】:

我有一个问题,事件被正确触发,但数据没有从Broadcast::channel 方法内的授权回调函数返回。

事件如下所示:

public function __construct($userId, $message, $username, $profileImg, $fixtureId)
{
    $this->message = $message;
    $this->username = $username;
    $this->profileImg = $profileImg;
    $this->userId = $userId;
    $this->fixtureId = $fixtureId;
}

频道(状态)是这样创建和广播的:

public function broadcastOn()
{
    return new PresenceChannel('fixture-channel.' . $this->fixtureId);
}

然后在BroadcastServiceProvider 类中,我称之为:

public function boot()
{

    Broadcast::routes(['middleware' => ['auth']]);

    require base_path('routes/channels.php');
}

问题函数所在的channels.php 文件如下所示:

Broadcast::channel('fixture-channel.{fixtureId}', function ($user, $fixtureId, $message, $username, $profileImg, $userId) {
    DB::table('test')->insert(array('id' => '4'));
    return [
        'message' => $message, 
        'username' => $username, 
        'profileImg' => $profileImg, 
        'userId' => $userId, 
        'fixtureId' => $fixtureId
    ];
});

如您所见,我试图在回调函数中插入一些数据,但这从未发生过。在回调函数之外,数据插入成功。我还尝试了一个回调函数,其中只定义了 userfixtureId - 没有成功。

提前谢谢你。

【问题讨论】:

    标签: javascript php laravel laravel-echo


    【解决方案1】:

    据我所知,channel.php 代表Authorization Logic

    您返回数据的位置是broadcastWith() - 或者如果您没有broadcastWith() 方法,则会推送公共属性。

    应该是这样的:

    channels.php中,是为了socket通道的授权,所以应该返回一个布尔值。

    Broadcast::channel('fixture-channel.{fixtureId}', function ($user, $fixtureId) {
        return $user->canAccess($fixtureId);
        // this should return a boolean.
    });
    

    其余的都可以在构造中完成。无论您的任何属性被定义为公共,都将被推送。

    public $message;
    public $username;
    // etc..
    
    public function __construct($userId, $message, $username, $profileImg, $fixtureId)
    {
        $this->message = $message;
        $this->username = $username;
        $this->profileImg = $profileImg;
        $this->userId = $userId;
        $this->fixtureId = $fixtureId;
    }
    

    (可选)假设您只想推送messageusername,然后使用broadcastWith()

    public function broadcastWith() {
       return [
         'message' => $this->message,
         'username' => $this->username
       ]
    }
    

    如果目的是在广播消息时写入数据库,你可以把它放在里面

    public function broadcastOn()
    {
        \DB::table('test')->insert(array('id' => '4'));
    
        return new PresenceChannel('fixture-channel.' . $this->fixtureId);
    }
    

    【讨论】:

    • 好吧,如果你看一下 Laravel 广播文档,他们会像我一样做,虽然我同意,你的方式看起来更好。问题是,从未调用过身份验证代码。我认为这是因为 Echo.join 方法没有尝试连接到频道 - 不知道为什么。
    • 你知道为什么它没有被调用吗?有同样的问题
    • 您是否输入了Log::info('xx') 并查看它是否真的被调用了?这可能是个问题。此外,channels.php 路由应该返回一个布尔值。
    猜你喜欢
    • 1970-01-01
    • 2017-07-26
    • 2013-04-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多