Laravel is a popular PHP web framework used for developing robust and scalable web applications. It comes with several built-in features that simplify the development process, including authentication and authorization. One of the most critical aspects of authentication is user verification. In this article, we will explore how to add Textlocal OTP verification in Laravel 8 with an example.
Textlocal is a cloud-based messaging service that provides APIs to send SMS and OTP (One Time Password) messages. Textlocal OTP verification is a secure way of verifying user identity by sending a unique code to their mobile number or email address. It’s a widely used method for two-factor authentication, which adds an extra layer of security to your web application.
Prerequisites
Before we start, you need to have a basic understanding of Laravel, PHP, and MySQL. You also need to have the following installed on your machine:
- Laravel 8
- Composer
- Textlocal account
- Textlocal API key
Step 1: Install Laravel 8
If you haven’t installed Laravel 8 on your machine, open your terminal and run the following command:
composer create-project --prefer-dist laravel/laravel otp-verification
This command will create a new Laravel project called otp-verification.
Read Also : how to implement mobile otp verification in laravel 8 step by step
Step 2: Set up the Database
Laravel uses the .env file to store configuration variables, including database credentials. Open the .env file and update the following variables:
DB_CONNECTION=mysqlDB_HOST=127.0.0.1DB_PORT=3306DB_DATABASE=otp_verificationDB_USERNAME=rootDB_PASSWORD=
This configuration assumes that you’re using MySQL as your database server. Replace the database credentials with your own.
Next, create a new database called otp_verification in MySQL.
Step 3: Install the Textlocal PHP SDK
Textlocal provides a PHP SDK that allows you to interact with their API. To install the Textlocal PHP SDK, run the following command in your terminal:
composer require textlocal/textlocal
This command will install the Textlocal PHP SDK and its dependencies in your Laravel project.
Read Also : nexmo sms otp verification in laravel 8
Step 4: Create the Route
Open the routes/web.php file and add the following route:
Route::get('/verify', 'Auth\VerificationController@showVerificationForm');Route::post('/verify', 'Auth\VerificationController@verify');
This route defines two endpoints: /verify and /verify (POST). The first endpoint shows the verification form to the user, and the second endpoint handles the form submission.
Step 5: Create the Controller
Create a new controller called VerificationController by running the following command in your terminal:
php artisan make:controller Auth/VerificationController
This command will create a new controller file called VerificationController.php in the app/Http/Controllers/Auth directory.
Open the VerificationController.php file and add the following code:
<?phpnamespace App\Http\Controllers\Auth;use App\Http\Controllers\Controller;use Illuminate\Http\Request;use Illuminate\Support\Facades\Auth;use Textlocal\Textlocal;use Textlocal\RestClient;use Textlocal\exceptions\RestException;class VerificationController extends Controller{ public function showVerificationForm() { return view('auth.verify'); } public function verify(Request $request) { $otp = rand(100000, 999999); $mobileNumber = $request->mobile_number; $apiKey = env('TEXTLOCAL_API_KEY'); // Send the OTP via Textlocal $textlocal = new Textlocal(false, false, $apiKey); $numbers = array($mobileNumber); $sender = 'TXTL';// Set the message $message = "Your verification code is: " . $otp;try { $response = $textlocal->sendSms($numbers, $message, $sender); } catch (RestException $ex) { return redirect('/verify')->with('error', 'Something went wrong! Please try again later.'); } // Save the OTP in the database $request->session()->put('otp', $otp); return redirect('/verify')->with('success', 'OTP has been sent to your mobile number.');}}
This controller has two methods: showVerificationForm and verify. The showVerificationForm method returns the verification form view, while the verify method sends the OTP via Textlocal and saves it in the session.
Step 6: Create the View
Create a new view file called verify.blade.php in the resources/views/auth directory and add the following code:
@if (session('success')) <div class="alert alert-success"> {{ session('success') }} </div>@endif@if (session('error')) <div class="alert alert-danger"> {{ session('error') }} </div>@endif<form method="POST" action="/verify"> @csrf <div class="form-group"> <label for="mobile_number">Mobile Number</label> <input type="text" name="mobile_number" id="mobile_number" class="form-control" required> </div> <button type="submit" class="btn btn-primary">Send OTP</button></form>
This view file displays a form to the user to enter their mobile number and submit it. It also displays success and error messages if any.
Step 7: Verify the OTP
Now, we need to add the OTP verification logic to the controller. Open the VerificationController.php file and update the verify method as follows:
public function verify(Request $request){ $otp = $request->otp; $sessionOtp = $request->session()->get('otp'); if ($otp == $sessionOtp) { // OTP matched return redirect('/dashboard'); } else { // OTP didn't match return back()->with('error', 'Invalid OTP!'); }}
This code checks if the OTP entered by the user matches the OTP saved in the session. If it matches, it redirects the user to the dashboard. Otherwise, it displays an error message.
Step 8: Update the View
Update the verify.blade.php file to display the OTP field:
@if (session('success')) <div class="alert alert-success"> {{ session('success') }} </div>@endif@if (session('error')) <div class="alert alert-danger"> {{ session('error') }} </div>@endif<form method="POST" action="/verify"> @csrf <div class="form-group"> <label for="mobile_number">Mobile Number</label> <input type="text" name="mobile_number" id="mobile_number" class="form-control" required> </div> <div class="form-group"> <label for="otp">OTP</label> <input type="text" name="otp" id="otp" class="form-control" required> </div> <button type="submit" class="btn btn-primary">Verify OTP</button></form>
This code adds a new input field for OTP verification.
Step 9: Test the Application
Now, we’re ready to test our OTP verification application. Run the following command in the terminal to start the server:
php artisan serve
Then, open your web browser and navigate to http://localhost:8000. You should see the verification form. Enter your mobile number and click the Send OTP button.
If everything is set up correctly, you should receive an SMS on your mobile phone with the OTP. Enter the OTP in the form and click the Verify OTP button. If the OTP is correct, you should be redirected to the dashboard. Otherwise, an error message will be displayed.
Conclusion
In this tutorial, we have learned how to add mobile OTP verification to a Laravel 8 application using Textlocal. We have covered the following steps:
- Install the Textlocal SDK
- Configure the Textlocal credentials
- Create a route for the verification form
- Create the verification form view
- Create a controller to handle the form submission
- Create the view to display the OTP field
- Verify the OTP entered by the user
- Test the application
We hope this tutorial has been helpful in adding OTP verification to your Laravel 8 application.
Comments
Post a Comment