'How can i set expire time in otp in laravel8?

When i am trying to expiry otp, is not working but i do not know what i am doing wrong. I set expiry time with Carbon but still not working. What should i do?. It needs config in app/config or something?

This is a part of my controller code

            if(!$device_serial_number)
            {
              return ('error');
            } else {
              $otp = rand(100000,999999);
  //            Cache::put([$otp], now()->addSeconds(20));

              $otp_expires_time = Carbon::now()->addSeconds(20);
              Cache::put(['otp_expires_time'], $otp_expires_time);
              Log::info("otp = ".$otp);

              $user = User::where('phonenumber', $request->phonenumber)->update(['otp' => $otp]);
              $token = auth()->user()->createToken('Laravel Password Grant Client')->accessToken;
      //        Log::info($request);
      //        $user = User::where([['phonenumber', '=', request('phonenumber')],['otp','=', request('otp')]])->first();

              return response()->json(array(
                'otp_expires_at'=> $otp_expires_time,
                'otp' => $otp,
                'token' => $token));

This is a part of my middleware code

  Log::info($request);
  $user = User::where([['phonenumber', '=', request('phonenumber')],['otp','=', request('otp')],['otp_expires_time', '=', request('otp_expires_time')]])->first();
  $otp_expires_time = Carbon::now()->addSeconds(20);
  if($user)
  {
    if(!$otp_expires_time > Carbon::now())
    {
      return response('the time expired');
    } else {

      Auth::login($user, true);

      return response()->json(array(
      'message' => 'You are logged in',
      ['user' => auth()->user()]));

      return response('You are logged in');


Solution 1:[1]

$otp = rand(1000,9999);

Cache::put([$otp], now()->addSeconds(10));

$otp_expires_time = Carbon::now('Asia/Kolkata')->addSeconds(10);


      Log::info("otp = ".$otp);
      Log::info("otp_expires_time = ".$otp_expires_time);
      Cache::put('otp_expires_time', $otp_expires_time);
      $user = User::where('email','=',$request->email)->update(['otp' => $otp]);
      $user = User::where('email','=',$request->email)->update(['otp_expires_time' => $otp_expires_time]);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 mohan balaji