当我将数组作为参数传递给TeamMemberUpdating
事件时,出现以下错误:
传递给App \ Events \ Event :: __ construct()的参数1必须是App \ Models \ Model的实例,给出的Illuminate \ Database \ Eloquent \ Collection的实例
在这里我触发事件:
$teamMembers = TeamMember::whereIn('email', $request->projectTeamEmails)->get();
event(new TeamMemberUpdating($teamMembers));
我的活动:
class TeamMemberUpdating
{
use Dispatchable, InteractsWithSockets, SerializesModels;
public $teamMembers;
/**
* Create a new event instance.
*
* @return void
*/
public function __construct(TeamMember $teamMembers)
{
$this->teamMembers = $teamMembers;
}
}
还有我的监听器handle()
方法:
public function handle(TeamMemberUpdating $event)
{
TeamMemberLog::insert($event->teamMembers);
}
答案 0 :(得分:1)
您的事件类被定义为不处理数组,构造函数严格提示TeamMember
的单个实例
public function __construct(TeamMember $teamMembers)
{
$this->teamMembers = $teamMembers;
}
您可以将其更改为:
public function __construct($teamMembers)
{
$this->teamMembers = $teamMembers;
}
这样,它将同时接受单个TeamMember
和一个Collection
团队成员。您可以进行instanceof
检查以确定传入的内容。
或者,您可以更改调度方法:
$teamMembers = TeamMember::whereIn('email', $request->projectTeamEmails)->get();
$teamMembers->each(function ($teamMember) {
event(new TeamMemberUpdating($teamMember));
});
这将为每个模型实例调度一个事件