【发布时间】:2020-11-23 06:20:54
【问题描述】:
我正在尝试通过 laravel 中的推送器广播消息,但出现以下错误:
Symfony\Component\Debug\Exception\FatalThrowableError · Too few arguments to function
App\Providers\BroadcastServiceProvider::{closure}(), 1 passed in
laravel/framework/src/Illuminate/Broadcasting/Broadcasters/Broadcaster.php on line 77 and exactly 2
expected routes/channels.php:33App\Providers\BroadcastServiceProvider::{closure}
});
它发生的代码如下
Broadcast::channel('conversations.{id}', function ($user, $id) {
return $user->inConversation($id);
});
我有另一个频道,它工作正常
Broadcast::channel('users.{id}', function ($user, $id){
return (int) $user->id === (int) $id;
});
不知道为什么参数太少
*** 更新 *** 我正在使用 laravel livewire。
事件类如下:
class MessageAdded implements ShouldBroadcast
{
use Dispatchable, InteractsWithSockets, SerializesModels;
public $message;
/**
* Create a new event instance.
*
* @param Message $message
*/
public function __construct(Message $message)
{
$this->message = $message;
}
public function broadcastWith()
{
return [
'message' => [
'id' => $this->message->id
]
];
}
/**
* Get the channels the event should broadcast on.
*
* @return \Illuminate\Broadcasting\Channel|array
*/
public function broadcastOn()
{
return new PrivateChannel('conversations.' . $this->message->conversation->id);
}
}
laravel livewire 函数如下:
public function reply()
{
$this->validate([
'body' => 'required'
]);
$message = $this->conversation->messages()->create([
'user_id' => auth()->id(),
'body' => $this->body
]);
$this->conversation->update([
'last_message_at' => now()
]);
foreach ($this->conversation->others as $user) {
$user->conversations()->updateExistingPivot($this->conversation, [
'read_at' => null
]);
}
broadcast(new MessageAdded($message))->toOthers();
$this->emit('message.created', $message->id);
$this->body = '';
}
问候 丹尼
【问题讨论】:
-
可以添加事件类和控制器吗?
-
你能在
broadcast(new MessageAdded($message))->toOthers();之前dd($message);在livewire 中 -
看起来对话 id 没有被传递。
-
这是数据 "user_id" => 1 "body" => "fff" "conversation_id" => 1 "updated_at" => "2020-08-03 19:15:59" " created_at" => "2020-08-03 19:15:59" "id" => 16 conversation_id 已设置
-
抱歉来晚了,关于上面的数据结构,我认为
$this->message->conversation->id在BroadcastOn方法中应该是$this->message->conversation_id?