Are OTP for user registration supposed to store in session or datbase in laravel?

Are OTP supposed to store in session or database. Can anyone please tell the flow of OTP. As Far as i understood, when a user submits the necessary field the user details and the otp gets stored in database, and after register another form opens to enter otp and then the registration finally success. But I dont get the actual logic. To store the otp we need to store all the data in database, all the data gets stored (user info) only then we can verify the otp. I am using session but I am not sure if the code is correct,

    public function otpVerify(Request $request)
        $data = $request->validate([
            'verification_code' => ['required', 'numeric'],
            'phone_number' => ['required', 'string'],
        $otp = $request->session()->get('otp');
        $enteredOtp = $request->session()->get('otp');

    if ($otp == $enteredOtp) {
        $user = tap(User::where('phone_number', $data['phone_number']));
        // ->update(['isVerified' => true]);
        return success([
        ], __('User created successfully'));
 } else {
    return problem([], 500, 'OTP Doesnt Match');

  public function register(RegisterUserRequest $request)
        $user = new User($request->validated());
        $otp = rand(10000, 99999);
        $otp_expires_time = Carbon::now()->addSeconds(20);
        if (!env('APP_ENV') === 'local') {

            $sms = AWS::createClient('sns');

                'Message' => 'Your OTP code is:' + $otp,
                'PhoneNumber' => $user->phone_number,
                'MessageAttributes' => [
                    'AWS.SNS.SMS.SMSType'  => [
                        'DataType'    => 'String',
                        'StringValue' => 'Transactional',
        } else {
            Log::channel('otplog')->info('Your OTP code is:'. $otp);
        $status = $user->save();
        $success['token'] =  $user->createToken('MyAuthApp')->plainTextToken;
        $success['name'] =  $user->name;
        Session::put('OTP', $otp, 'expiry_time',$otp_expires_time);
        if ($status) {
            return success([
            ], __('User created successfully'));
        } else {
            return problem([], 500, 'USER_REGISTER_FAIL');


Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

Store in database is a good option

All methods was sourced from or, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Notify of

Inline Feedbacks
View all comments
Would love your thoughts, please comment.x