javascript - Broadcast::channel回调函数没有被调用

标签 javascript php laravel laravel-echo

我遇到一个问题,事件已正确触发,但数据未从 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;
}

channel (存在)的创建和广播如下:

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 的回调函数 - 没有成功。

提前谢谢您。

最佳答案

据我所知,channel.php 适用于 Authorization Logic

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

应该是这样的:

channels.php中,它用于套接字 channel 的授权,因此它应该返回一个 bool 值。

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

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

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;
}
<小时/>

或者,假设您只想推送消息用户名,然后使用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);
}

关于javascript - Broadcast::channel回调函数没有被调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59347105/

相关文章:

laravel - 来自私有(private)仓库的 Composer 创建项目

javascript - 查找特定结束标记旁边的 HTML 元素

javascript - 调整页面大小时,jquery-bootstrap 菜单不会更改

php - MySQL:选择包含ID的所有行

php - 将 PHP 数组传递到 Javascript

php - Laravel 调度程序未按预期工作

javascript - 如何使自动完成建议可点击?

javascript - JavaScript/rails 中的文档预览库

php - Janrain 导入联系人 API 需要 PRO 类型的账号吗?

php - Laravel 5 Auth 注销不工作