1. Go to this page and download the library: Download abdullahfaqeir/laravel-otp library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
abdullahfaqeir / laravel-otp example snippets
/**
* Send OTP via SMS.
*/
OTP()->send('+989389599530');
// or
OTP('+989389599530');
/**
* Send OTP via channels.
*/
OTP()->channel(['otp_sms', 'mail', \App\Channels\CustomSMSChannel::class])
->send('+989389599530');
// or
OTP('+989389599530', ['otp_sms', 'mail', \App\Channels\CustomSMSChannel::class]);
/**
* Send OTP for specific user provider
*/
OTP()->useProvider('admins')
->send('+989389599530');
/**
* Validate OTP
*/
OTP()->validate('+989389599530', 'token_123');
// or
OTP('+989389599530', 'token_123');
// or
OTP()->useProvider('users')
->validate('+989389599530', 'token_123');
namespace App\Models;
use AbdullahFaqeir\OTP\Concerns\HasOTPNotify;
use AbdullahFaqeir\OTP\Contracts\OTPNotifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
class User extends Authenticatable implements OTPNotifiable
{
use Notifiable;
use HasOTPNotify;
// ...
}
namespace App;
use AbdullahFaqeir\OTP\Contracts\SMSClient;
use AbdullahFaqeir\OTP\Notifications\Messages\MessagePayload;
class SampleSMSClient implements SMSClient
{
public function __construct(protected SampleSMSService $SMSService)
{
}
public function sendMessage(MessagePayload $payload): mixed
{
return $this->SMSService->send($payload->to(), $payload->content());
}
// ...
}
namespace App\Http\Controllers;
use App\Models\User;
use AbdullahFaqeir\OTP\Exceptions\InvalidOTPTokenException;
use AbdullahFaqeir\OTP\OTPBroker as OTPService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Throwable;
class AuthController
{
public function __construct(private OTPService $OTPService)
{
}
public function sendOTP(Request $request): JsonResponse
{
try {
/** @var User $user */
$user = $this->OTPService->send($request->get('mobile'));
} catch (Throwable $ex) {
// or prepare and return a view.
return response()->json(['message'=>'An unexpected error occurred.'], 500);
}
return response()->json(['message'=>'A token has been sent to:'. $user->mobile]);
}
public function verifyOTPAndLogin(Request $request): JsonResponse
{
try {
/** @var User $user */
$user = $this->OTPService->validate($request->get('mobile'), $request->get('token'));
// and do login actions...
} catch (InvalidOTPTokenException $exception){
return response()->json(['error'=>$exception->getMessage()],$exception->getCode());
} catch (Throwable $ex) {
return response()->json(['message'=>'An unexpected error occurred.'], 500);
}
return response()->json(['message'=>'Logged in successfully.']);
}
}