首页 > 解决方案 > 通过 API 将登录 OTP 插入到我的数据库的“OTP”列中以获取所请求的电子邮件

问题描述

我的 API 结果为 OTP,但它没有被插入到数据库中。如果作为输入提供的电子邮件是数据库中已经存在的有效电子邮件,我将尝试生成一个 OTP 并将其保存到表中的OTP列中users。它更像是一个登录 OTP API,其中 otp 只是被插入到数据库中,而不是发送到手机号码或电子邮件 ID。有人猜我哪里错了吗?我只是 REST API 的初学者。所以,需要帮助解决这个问题。

public function sendotp(Request $request){
            
            $validator = Validator::make
            ($request->all(),
                [
                    'email'    => 'required|email',
                ]
            );
    
            if ($validator->fails()) {
                return response()->json(
                    [$validator->errors()],
                    422
                );
            }
            
            
            $email_user = User::where('email',$request->email)->first();
            if($email_user){
    
                $otp = rand(1000,9999);
                
    
                $user = User::where('email','=',$request->email)->update(['OTP' => $otp]);
                $user->save();
               return response()->json($otp);
            }
            else{
    
                return response()->json(['message'=>'No users exists with this email'], 404);
            }
            
        }

标签: phplaravelcrudlaravel-8rest

解决方案


您在更新之前返回响应所以更改如下

$user = User::where('email',$request->email)->first();
   if($user){
    
       $otp = rand(1000,9999);
       $user->OTP=$otp;
       $user->save();
       return response()->json($otp);
    
               
    } else{

      return response()->json(['message'=>'No users exists with this email'], 404);
   }

还要确保您是否正在更新,然后在模型中使列OTP可填充 User


推荐阅读