How to send OTP in the email on registration using Laravel API

if you want to apply send OTP on user registration and after OTP verify make and update to true is_email_verified field in users table. user can able to login if field is_email_verified is true .I understand you have already is_email_verified in users table.

Step 1.

I am creating new migration for adding new field in users table called “otp”. I run below command to command panel.

php artisan make:migration add_otp_users_table

it will create migration under folder database\migrations file name is 2023_01_13_074501_add_otp_users_table.php

2023_01_13_074501_add_otp_users_table.php

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class AddOtpUsersTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
         Schema::table('users', function (Blueprint $table) {
             $table->string('otp')->nullable()->after('remember_token');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('users', function (Blueprint $table) {
              $table->dropColumn('otp');
        });
    }
}

after that we need run command “php artisan migrate” then it will create new column in users table called “otp”.

Step 2. Create Routes for API

you need to create routes in api.php file.

<?php use App\Http\Controllers\API\UserController;
Route::group(['namespace'=>'API'], function(){
	Route::group([
	  //'prefix' => 'auth'
	], function() {
		Route::post('register', [UserController::class, 'register'])->name('register');
		Route::post('verify_otp', [UserController::class, 'verify_otp'])->name('verify_otp');
	});
});

Step 3. register send otp functionality

<?php
namespace App\Http\Controllers\API;
use Illuminate\Http\Request; 
use App\Http\Controllers\Controller; 
use App\Models\User;
use Illuminate\Support\Facades\Auth; 
use Validator;
use Illuminate\Support\Facades\Hash;
use Mail; 
use Illuminate\Support\Str;
use DB;
use Carbon\Carbon;
class UserController extends Controller 
{

  /** 
     * Register api 
     * 
     * @return \Illuminate\Http\Response 
     */ 
    public function register(Request $request) 
    { 
        $validator = Validator::make($request->all(), [ 
            'name' => 'required', 
            'email' => 'required|email|unique:users', 
            'password' => 'required|min:8', 
            'c_password' => 'required|same:password', 
        ]);
    if ($validator->fails()) { 
            return response()->json(['status'=>false,'message'=>$validator->errors()->first()]);             
            }
    $input = $request->all(); 
        $otp = rand(1000,9999);
        $user = User::create([
            'name' => $request->name,
            'email' => $request->email,
            'password' => Hash::make($request->password),
            'otp'=>$otp,
        ]);
         if($user){           
              Mail::send('emails.OTPVerificationEmail', ['otp' => $otp], function($message) use($request){
                  $message->to($request->email);
                  $message->subject('OTP Received for account verification');
            });
           
             return response()->json(["status" => true, "message" => "OTP sent successfully"]);
        }
        else{
             return response()->json(["status" => false, 'message' => 'failed']);
        } 
    }

  }

here, I have generated random number with this code $otp = rand(1000,9999); . I have applied some validation on email fields like required, check email unique, and valid email address.
path – http://localhost/websitename/api/register
parameter – name, email, password, c_password

here, I have used email template called OTPVerificationEmail.blade.php here we need to define otp so it will show on email.
OTPVerificationEmail.blade.php

Your OTP is : <?php echo $otp; ?>

Step 4. verify OTP

after received OTP you need to verify OTP with other API called “verify_otp”.
you need to add one more function under UserController.php file.

/** 
     * verify_otp api 
     * 
     * @return \Illuminate\Http\Response 
     */ 
    public function verify_otp(Request $request) 
    { 
        $validator = Validator::make($request->all(), [ 
            'email' => 'required|email', 
            'otp' => 'required', 
        ]);
        if ($validator->fails()) { 
           return response()->json(['status'=>false,'message'=>$validator->errors()->first()]);             
        }
        $user  = User::where([['email','=',$request->email],['otp','=',$request->otp]])->first();
        if($user){
            User::where('email','=',$request->email)->update(['otp' => null,'is_email_verified'=>true]);
            $user_data  = array('id'=>$user->id,'name'=>$user->name,'email'=>$user->email);
            $success['status'] = true;             
            $success['user'] =$user_data;
            $success['message'] = "Your e-mail is verified. You can now login.";
            $message = "Your e-mail is verified. You can now login.";
                 try {
                    $to_address=$user->email;
                    $verification_data=array('email' =>$user->email,
                                             'name' => $user->name);
                    $varifyemail= \Mail::send('emails.registrationEmail', ['verification'=>$verification_data], function($message) use ($to_address) { $message->to($to_address)->subject('Congratulation, on verifying your account'); });
                 
                }
                  catch(Exception $e) {
               }
            return response()->json($success, $this->successStatus);
        }
        else{
             return response()->json(["status" => false, 'message' => 'Invalid OTP']);
        }

    }

path – http://localhost/websitename/api/verify_otp
parameter – email, otp
here I have also used on more email template registrationEmail.blade.php after account verification it will send user information like name, email and id. if otp will verify/check from database column otp will be set to null.

Correct OTP –
you will get status true and message “Your e-mail is verified. You can now login.“ also it will give some user detail like id, name, email.

Leave a Reply

Your email address will not be published. Required fields are marked *

98 − 91 =