Level 73
I would suggest using the official Jetstream package instead of implementing it yourself
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
Hi,
I implemented Two Factor Authentication using session in Laravel.
public function verifyPhone(Request $request)
{
if (!$request->session()->has('code')) {
return redirect()->back()->withErrors('OTP Exprired. Please resend the code.');
}
if ($request->session()->has('code_sent_at')) {
$code_sent_at = $request->session()->get('code_sent_at');
if ($code_sent_at->diffInSeconds() > 300) {
$this->clearCode($request);
return redirect()->back()->withErrors('OTP has been expired. Try again.');
}
}
if ($request->session()->has('attempt')) {
$attempt = $request->session()->get('attempt');
if ($attempt > 2) {
$this->clearCode($request);
return redirect()->back()->withErrors('Exceeded maximum attempts. Try again.');
}
}
$code = $request->session()->get('code');
$otp = $request->otp;
if ($code == $otp) {
$request->user()->forceFill([
'phone_verified_at' => now(),
])->save();
$this->clearCode($request);
return redirect()->back()->withStatus('Phone number verified successfully.');
} else {
$attempt = $request->session()->get('attempt');
$request->session()->put('attempt', $attempt + 1);
return redirect()->back()->withErrors('Invalid OTP. Try again.');
}
}
Is it secure to store these values in session?
If it is bad practice, then may I know the reasons?
Please or to participate in this conversation.