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

Laravel中出现Attempt to read property 'email' on null错误的求助

问题:调用$std->email时触发「Attempt to read property 'email' on null」错误

应用验证规则时,输入空邮箱或错误邮箱地址会出现该错误,尝试多种方法仍无法解决。

我的Password Controller代码:

public function otpSend(Request $request)
{

    $otp = rand(10000, 99999);
    $std = Student::where('email', '=', $request->email)->first();
    $rules = Validator::make($request->all(), [
        'email' => 'required|email',
    ]);
   $email = Mail::to($std->email)->send(new MailVerifyOtp($otp));
    if ($rules->fails()) {
        return response([
            "code" => 400,
            "message" => "Email Not Exist",
        ]);
    } else {
        return response([
            "code" => 200,
            "message" => "OTP send Successfully",
            "otp" => $otp,
        ]);

    }
}

错误触发场景

输入空邮箱或不存在的邮箱地址时触发该错误:
输入空或错误邮箱时触发错误的截图


解决方案

错误根源是代码执行顺序逻辑错误:

  1. 先查询Student记录,再做输入验证,最后才判断验证结果
  2. 当邮箱为空或不存在时,$std = Student::where(...) ->first()会返回null,此时调用$std->email必然报错

调整代码执行顺序,修正后的代码如下:

public function otpSend(Request $request)
{
    // 1. 先做输入验证
    $rules = Validator::make($request->all(), [
        'email' => 'required|email',
    ]);

    if ($rules->fails()) {
        return response([
            "code" => 400,
            "message" => "邮箱格式不正确或未填写",
        ]);
    }

    // 2. 验证通过后,查询学生是否存在
    $std = Student::where('email', $request->email)->first();
    
    if (!$std) {
        return response([
            "code" => 400,
            "message" => "该邮箱未注册",
        ]);
    }

    // 3. 学生存在时,生成OTP并发送邮件
    $otp = rand(10000, 99999);
    Mail::to($std->email)->send(new MailVerifyOtp($otp));

    return response([
        "code" => 200,
        "message" => "OTP发送成功",
        "otp" => $otp,
    ]);
}

关键修正点:

  • 调整执行顺序:先验证输入合法性,再查询用户,最后执行发送邮件操作
  • 增加存在性判断:查询后判断$std是否为null,避免调用空对象的属性
  • 优化错误提示:区分「格式错误/未填写」和「邮箱未注册」两种场景,提示更清晰

内容的提问来源于stack exchange,提问作者SAH Services

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 01:40:45