Laravel发送邮件报错Undefined variable: isi_email1的解决方法
Laravel邮件发送报错
Undefined variable: isi_email1修复方案 你在实现Laravel向other_emails发送邮件的功能时,出现Undefined variable: isi_email1错误,核心原因是邮件类构造函数未正确接收传入变量,同时控制器查询逻辑存在疏漏,以下是具体修复步骤:
1. 修复邮件类构造函数
你的OthersEmail类构造函数未声明接收参数,直接使用未定义的$isi_email1变量,导致报错。修改构造函数,添加参数并完成赋值:
public $isi_email1; use Queueable, SerializesModels; /** * Create a new message instance. * * @return void */ public function __construct($isi_email1) { $this->isi_email1 = $isi_email1; } /** * Build the message. * * @return $this */ public function build() { return $this->from('admin@pinnuss.com') ->subject('Thank you') ->view('other_email'); }
2. 修复控制器查询与循环逻辑
- 原查询仅构建了语句,未执行获取数据,需添加
->get()方法 - 循环中需明确获取
other_emails字段值,而非直接传入模型对象 - 建议增加非空校验,避免无效邮箱导致的报错
修改后的控制器代码:
$isi_email1 = [ 'title'=>'Thank you for your purchase', 'body'=>'Please give us your review about your experience using Pintunuswantara Travel. Link : https://pintunuswantara.com/review' ]; // 给用户1发送邮件 Mail::to($booking->email)->send(new OthersEmail($isi_email1)); // 获取所有包含other_emails的记录 $others = Booking::select('other_emails')->get(); foreach($others as $other){ // 校验邮箱非空 if(!empty($other->other_emails)){ Mail::to($other->other_emails)->send(new OthersEmail($isi_email1)); } }
额外优化:处理多邮箱场景
如果other_emails字段存储的是逗号分隔的多个邮箱,需拆分后逐个发送:
foreach($others as $other){ if(!empty($other->other_emails)){ $emails = explode(',', $other->other_emails); foreach($emails as $email){ $trimmedEmail = trim($email); // 校验邮箱格式有效性 if(filter_var($trimmedEmail, FILTER_VALIDATE_EMAIL)){ Mail::to($trimmedEmail)->send(new OthersEmail($isi_email1)); } } } }
内容的提问来源于stack exchange,提问作者Nicho
相关产品推荐
相关产品推荐

