How to Send OTP in Email in Laravel 10


Hello there! In this article, I'll walk you through the process of sending One-Time Passwords (OTPs) via email using the Laravel framework. OTPs add an extra layer of security to your application, and integrating them with email is a reliable method to ensure secure user authentication

So, let's see how to send OTP in email in laravel 10, laravel send OTP in mail, email verification in laravel 10, how to generate OTP in laravel 8/9/10, how to send OTP email using laravel 8/9/10.

Step 1: Set Up Your Laravel Project

Firstly, make sure you have a Laravel project up and running. If not, you can create one using the following command:

composer create-project --prefer-dist laravel/laravel your-project-name

Navigate to your project directory:

cd your-project-name

 

Step 2: Configure Mail Settings

Open the .env file in your project root and configure your mail settings. Set the MAIL_DRIVER to 'smtp' and provide the necessary details for your SMTP server:

MAIL_DRIVER=smtp
MAIL_HOST=your-smtp-host
MAIL_PORT=your-smtp-port
MAIL_USERNAME=your-smtp-username
MAIL_PASSWORD=your-smtp-password
MAIL_ENCRYPTION=tls

 

Step 3: Create a Controller

Generate a new controller using the Artisan command:

php artisan make:controller OtpController

This command will create a new file at app/Http/Controllers/OtpController.php.

 

Step 4: Implement OTP Generation Logic

Open OtpController.php and add the following code to generate a random OTP and send it via email:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Mail;

class OtpController extends Controller
{
    public function sendOtp(Request $request)
    {
        $otp = rand(1000, 9999);

        Mail::send('emails.otp', ['otp' => $otp], function ($message) use ($request) {
            $message->to($request->input('email'))->subject('Your OTP');
        });

        return response()->json(['message' => 'OTP sent successfully']);
    }
}

resources/views/emails /otp.blade.php

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Sending OTP in Email Using Laravel 10 - Techsolutionstuff</title>
</head>
<body>
    <p>Dear User,</p>
    
    <p>Your One-Time Password (OTP) is: <strong>{{ $otp }}</strong></p>

    <p>Please use this OTP to complete your authentication process.</p>

    <p>Thank you,</p>
    <p>Your Application Team</p>
</body>
</html>

 

Step 5: Set Up Routes

Open routes/web.php and add a route to call the sendOtp method:

use App\Http\Controllers\OtpController;

Route::post('/send-otp', [OtpController::class, 'sendOtp']);

 

Step 6: Test the Implementation

Run your Laravel development server:

php artisan serve

Congratulations! You've successfully implemented OTP generation and email sending in Laravel 10.

 


You might also like:

RECOMMENDED POSTS

FEATURE POSTS