Hello developer! In this article, I'll walk you through the process of sending One-Time Passwords (OTPs) via email using the Laravel 10 and Laravel 11 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
In this guide, we'll create a controller and define the logic of generating OTP and sending OTP to email.
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
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
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
.
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>
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']);
Run your Laravel development server:
php artisan serve
Congratulations! You've successfully implemented OTP generation and email sending in Laravel 10 and Laravel 11.
You might also like: