粘贴数组作为Event的参数时出现错误

时间:2019-05-01 11:50:02

标签: php laravel event-listener

当我将数组作为参数传递给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);
}

1 个答案:

答案 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));
});

这将为每个模型实例调度一个事件