Closed jainnhimanshuu closed 2 years ago
Can please explain your desired flow ?
This package provides methods to send otps which is similar to calling a method on an instance. You can return response return view(...)
as you would normally do in a controller. To handle errors, simply wrap the sending logic into a try-catch block and return the error response.
I am using Axios to send and verify the OTP to create authentication. I need to get a response from the controller and redirect it to the dashboard. As I am new to the laravel, I can send and verify OTP with the help of the documentation, but I cannot figure out how I can achieve that. I hope I can explain the problem.
AuthController.php
public function loginWithMobile(LoginRequest $request)
{
$countryCode = $request->input('countryCode');
$mobileNumber = $request->input('mobileNumber');
$fullmobileNumber = $countryCode.$mobileNumber;
// Checking User
if (User::where('mobileNumber', $fullmobileNumber)->exists()) {
try {
$response = Msg91::otp()->to($fullmobileNumber)->send();
$statusCode = $response->getData();
return $statusCode;
} catch (\Craftsys\Msg91\Exceptions\ValidationException $e) {
} catch (\Craftsys\Msg91\Exceptions\ResponseErrorException $e) {
}
}else{
$userId = \Ramsey\Uuid\Uuid::uuid4()->toString();
User::Create([
'userId' => $userId,
'mobileNumber' => $fullmobileNumber
]);
Msg91::otp()
->to($fullmobileNumber)
->send();
}
}
As mentioned in the docs, you can handle the response and errors.
For your use case, following changes should be sufficient.
public function loginWithMobile(LoginRequest $request)
{
$countryCode = $request->input('countryCode');
$mobileNumber = $request->input('mobileNumber');
$fullmobileNumber = $countryCode.$mobileNumber;
// Create User if not exists
if (!User::where('mobileNumber', $fullmobileNumber)->exists()) {
$userId = \Ramsey\Uuid\Uuid::uuid4()->toString();
User::Create([
'userId' => $userId,
'mobileNumber' => $fullmobileNumber
]);
}
// send the OTP for mobile number verification
try {
$response = Msg91::otp()->to($fullmobileNumber)->send();
return ['message' => 'OTP successfully sent.'];
} catch (\Exception $e) {
// something went wrong with the OTP send process, return the error response
$error = \Illuminate\Validation\ValidationException::withMessages([
'mobileNumber' => $e->getMessage(),
]);
throw $error;
}
}
Hope it helps.
Closing because of inactivity. Feel free to re-open if it is not resolved.
I have read your documentation but am unable to understand, how I can send back the response if OTP is sent in laravel.