Spatie Laravel 9:如何给特定角色用户发送邮件通知?
问题分析与解决方案
你遇到的错误是因为当前代码中to参数传入的是Eloquent模型集合,而Laravel邮件的Envelope类要求to参数接收的是邮箱字符串数组或Address实例数组。
正确实现方式
将查询结果转换为纯邮箱字符串数组即可,具体修改如下:
- 移除不必要的
with("roles")(whereHas已经验证了角色关系,无需加载角色数据,节省性能) - 使用
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
相关产品推荐
相关产品推荐

