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, ]); } }
错误触发场景
输入空邮箱或不存在的邮箱地址时触发该错误:
解决方案
错误根源是代码执行顺序逻辑错误:
- 先查询
Student记录,再做输入验证,最后才判断验证结果 - 当邮箱为空或不存在时,
$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
相关产品推荐
相关产品推荐

