You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel中ChatEvent构造函数参数类型错误如何解决?

解决方法

错误原因很明确:ChatEvent的构造函数要求传入数组类型的参数,但你调用时通过json_encode($chat)把数组转成了JSON字符串,参数类型不匹配引发报错。

提供两种可行的解决思路:

方案一:直接传入数组(推荐)

事件类原本的设计就是接收数组,直接跳过JSON编码步骤,把构建好的$chat数组传给事件即可:

public function store(Request $request)
{
    $chat = [
        "to_user_id" => $request->to_user_id,
        "from_user_id" => $request->from_user_id,
        "message" => $request->message,
        "unread_thread_count" => $request->unread_thread_count,
        "read_status" => $request->read_status,
    ];

    event(new ChatEvent($chat)); // 直接传递数组,无需JSON编码
}

方案二:修改事件类适配字符串参数

如果业务逻辑确实需要事件中存储JSON格式的字符串,可以修改ChatEvent的构造函数,将参数类型改为字符串:

public $data;

public function __construct(string $data)
{
    $this->data = $data;
}

修改后,原调用代码中json_encode($chat)的写法就符合参数要求了。

内容的提问来源于stack exchange,提问作者Chanchal Kumar Mahto

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.21 11:06:26