John Davidson

php - check expire time for each verification code

0 comments
Message:


In the code below i check If there is a record for the user Check if ‍‍‍‍‍‍‍‍exprire_at is smaller than it is now, it will expire and create a new code, otherwise show the user a message.
But in both cases a new code is created
What is the problem


if (Auth::User()->numberVerifies()->where('type','mobile')->exists()) {

$expiry = optional(Auth::user()->numberVerifies()->where('type','mobile')->select('expire_at')->first())->expire_at;
if ($expiry < Carbon::now()) {
$code = rand(11111, 99999);
numVerify::create([
'user_id' => Auth::User()->id,
'type' => 'mobile',
'code' => $code,
'expire_at' => Carbon::now()->addSecond(60)
]);

session()->flash('messageMobile', 'code created.');

}
elseif ($expiry > Carbon::now()) {
session()->flash('messageMobile', 'you have a code');
}

}


My Answer:
The issue in your code is that you are creating a new verification code regardless of whether the existing code has expired or not. This is because you are checking the expiry time and creating a new code inside the same if statement.

To fix this issue, you should separate the code creation logic from the expiry check. Here is an updated version of your code:

php
if (Auth::User()->numberVerifies()->where('type','mobile')->exists()) {

$expiry = optional(Auth::user()->numberVerifies()->where('type','mobile')->select('expire_at')->first())->expire_at;

if ($expiry < Carbon::now()) {
$code = rand(11111, 99999);
numVerify::create([
'user_id' => Auth::User()->id,
'type' => 'mobile',
'code' => $code,
'expire_at' => Carbon::now()->addSecond(60)
]);

session()->flash('messageMobile', 'New code created.');
}
else {
session()->flash('messageMobile', 'You already have a code.');
}
}


With this updated code, a new verification code will only be created if the existing code has expired. Otherwise, the user will be notified that they already have a valid code.

Rate this post

3 of 5 based on 6233 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us