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

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 15:50:19