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

Spatie Laravel 9:如何给特定角色用户发送邮件通知?

问题分析与解决方案

你遇到的错误是因为当前代码中to参数传入的是Eloquent模型集合,而Laravel邮件的Envelope类要求to参数接收的是邮箱字符串数组或Address实例数组。

正确实现方式

将查询结果转换为纯邮箱字符串数组即可,具体修改如下:

  1. 移除不必要的with("roles")(whereHas已经验证了角色关系,无需加载角色数据,节省性能)
  2. 使用pluck('email')->toArray()替代get('email'),提取并转换为邮箱字符串数组

修改后的完整代码:

public function envelope()
{
    $recipientEmails = User::whereHas("roles", function($q) {
        $q->whereIn("id", [
            1, // Super Admin
            6, // Admin
            2, // Security Supervisor
            5, // Security Manager
        ]);
    })->pluck('email')->toArray();

    return new Envelope(
        from: 'amushref@hsse.co',
        to: $recipientEmails,
        subject: 'New Incident: ' . str_pad($this->record->ir_number, 4, '0', STR_PAD_LEFT) .
            ' - ' .
            $this->record->caseTypeRelationship->name .
            ' - ' . $this->record->locationRelationship->name,
    );
}

额外优化(可选)

如果担心存在空邮箱地址,可以添加过滤逻辑,确保只保留有效邮箱:

$recipientEmails = User::whereHas("roles", function($q) {
    $q->whereIn("id", [1,6,2,5]);
})->pluck('email')
  ->filter(fn($email) => !empty($email))
  ->toArray();

内容的提问来源于stack exchange,提问作者Abdulrahman Mushref

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 08:45:26