Laravel Cache Store OTP
March 12, 2025 · AI Conversations
### **Storing the OTP in Cache**
use IlluminateSupportFacadesCache;
$otp = rand(100000, 999999); // Generate a 6-digit OTP
$phone = '1234567890'; // Example identifier
Cache::put("otp_{$phone}", $otp, now()->addMinutes(10)); // Store OTP for 10 minutes
### **Retrieving the OTP from Cache**
$cachedOtp = Cache::get("otp_{$phone}");
if ($cachedOtp) {
return "Your OTP is: " . $cachedOtp;
} else {
return "OTP has expired or does not exist.";
}
### **Deleting the OTP After Verification**
Cache::forget("otp_{$phone}");
This ensures that the OTP expires automatically after 10 minutes. Let me know if you need further customization!
Handling OTP verification efficiently is crucial for security and user experience. Instead of storing OTPs in a database, Laravel’s caching system provides a lightweight and fast solution.
Here’s how you can store and validate OTPs using Laravel’s cache:
#### **🔹 Storing the OTP for 10 Minutes**
use IlluminateSupportFacadesCache;
$otp = rand(100000, 999999);
$phone = '1234567890';
Cache::put("otp_{$phone}", $otp, now()->addMinutes(10));
#### **🔹 Retrieving & Validating the OTP**
$cachedOtp = Cache::get("otp_{$phone}");
if ($cachedOtp) {
return "Your OTP is: " . $cachedOtp;
} else {
return "OTP has expired or does not exist.";
}
#### **🔹 Removing OTP After Verification**
Cache::forget("otp_{$phone}");
### **Why Use Laravel Cache for OTP?**
✅ **Faster than database storage**
✅ **Auto-expires after a set duration**
✅ **Lightweight & scalable solution**
Are you using caching for OTP management in your Laravel projects? Let’s discuss in the comments! 🚀 #Laravel #OTPVerification #WebDevelopment #PHP