我正在使用Laravel在一个非spa应用程序上使用vue 3。我也将Sanctum用于API,但不将其用于非SPA通信。
当我广播一个公共WebSocket事件时,我在前端接收到它,但是哇!我不能在所有通过一个单一的私人事件,没有收到在前端:
下面是我的代码:
从我的控制器发送的事件:
$text = text::where('text_name', $updatetext)->first();
if ($text) {
$text->update([
'data1' => $data1,
'data2' => $data1,
]);
$userIds = $text->users->pluck('id')->toArray();
// Trigger the event with the keyword ID and user IDs
event(new textUpdated($text->id, $userIds));
收到的事件ID:
<?php
namespace App\Events;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
use Illuminate\Queue\SerializesModels;
class textUpdated implements ShouldBroadcast
{
use SerializesModels;
public int $tries = 2;
public int $textId;
public array $userIds;
*/
public function __construct(int $textId, array $userIds)
{
$this->textId = $textId;
$this->userIds = $userIds;
}
/**
* Get the channels the event should broadcast on.
*
* @return array
*/
public function broadcastOn(): array
{
// Create private channels for each user ID in the array
$channels = [];
foreach ($this->userIds as $userId) {
$channels[] = new PrivateChannel("user.{$userId}");
}
return $channels;
}
/**
* Get the data to broadcast.
*
* @return array
*/
public function broadcastWith(): array
{
return [
'textId' => $this->textId
];
}
public function broadcastAs(): string
{
return 'text.updated';
}
}
Channell.php:
Broadcast::channel('user.{userId}', function ($user, $userId) {
return (int) $user->id === (int) $userId;
});
在vue js中:
created() {
window.Echo.private('user.' + this.userId)
.listen('.text.updated', (event) => {
console.log(event.textId); //Nothing received
});
}
请问如何解决这个问题?
奇怪的是,这只在私人渠道失败,而不是公共渠道。
谢谢你,谢谢
1条答案
按热度按时间taor4pac1#
答案是改变这一点:Broadcast::routes(“中间件”=>“验证:sanctum ']]);
public void run();
在BroadcastServiceProvider.php中