Home > Enterprise >  Attempt to read property "email" on null
Attempt to read property "email" on null

Time:09-21

When I apply validation rules in my code they give me this error I tried a lot to solve it but never get a solution. Below is my 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,
            ]);

        }
    }

When I enter an empty or wrong email address the showing me that error. Below is the attachment showing the error. When I enter an empty or wrong email address the showing me that error. Below is the attachment showing the error.

CodePudding user response:

I think issue was on below code

$std = Student::where('email', '=', $request->email)->first();

You did not pass any email in request that's why this line will throw an error. You have to put validation on starting of your code. Please update your code as below and check.

public function otpSend(Request $request){
    $rules = Validator::make($request->all(), [
        'email' => 'required|email',
    ]);
    if ($rules->fails()) {
        return response([
            "code" => 400,
            "message" => "Email Not Exist",
        ]);
    }

    $otp = rand(10000, 99999);
    $std = Student::where('email', '=', $request->email)->first();
   $email = Mail::to($std->email)->send(new MailVerifyOtp($otp));

        return response([
            "code" => 200,
            "message" => "OTP send Successfully",
            "otp" => $otp,
        ]);

}

  • Related