参数必须是 laravel 广播中消息的实例



当我设置广播时,出现此错误:

传递给 App\Events\MessagePosted::__construct(( 的参数 1 必须是 应用\事件\消息的实例,给定的应用\消息的实例, 在/var/www/epg/app/Http/Controllers/MessageController.php 中调用 第 25 行/var/www/epg/app/Events/MessagePosted.php#37

我从控制器触发这样的事件

broadcast(new MessagePosted($message, $user))->toOthers();

它应该将消息和用户广播到该事件

<?php
namespace AppHttpControllers;
use IlluminateHttpRequest;
use IlluminateSupportFacadesAuth;
use AppMessage;
use AppEventsMessagePosted;
class MessageController extends Controller
{
public function store(Request $request) 
{
$user = Auth::user();
// Store the new message
$message = $user->messages()->create([
'message' => $request->get('message')
]);
// Announce that a new message has been posted
broadcast(new MessagePosted($message, $user))->toOthers();
return ['status' => 'OK'];
}
}

我不明白发生了什么,因为我看到人们说检查你导入,但我在控制器中导入了正确的类。

确保MessagePosted文件与此类似

<?php
namespace AppEvents;
use AppUser; //your model
use AppMessage; //your model
use IlluminateBroadcastingChannel;
use IlluminateQueueSerializesModels;
use IlluminateBroadcastingPrivateChannel;
use IlluminateBroadcastingPresenceChannel;
use IlluminateFoundationEventsDispatchable;
use IlluminateBroadcastingInteractsWithSockets;
use IlluminateContractsBroadcastingShouldBroadcast;
class MessagePosted implements ShouldBroadcast
{
use Dispatchable, InteractsWithSockets, SerializesModels;
public $message;
public $user;
public function __construct(Message $message, User $user)
{
$this->message = $message;
$this->user = $user;
}
public function broadcastOn()
{
return new PrivateChannel('channel-name'); // your channel name
}
}

您正在将AppMessage传递到MessagePosted构造函数中。该错误指示您的MessagePosted正在接受AppEventsMessage而不是AppMessage。当你忘记在MessagePosteduse AppMessage时,往往会发生这种情况,因此它使用MessagePosted的命名空间,该命名空间AppEvents用于Message,导致AppEventsMessage

简而言之,use AppMessage在你的MessagePosted课上。

最新更新