I'm working with Laravel 5.8 and I'm trying to build my API for mobile app developer.
Basically I have made an API RegisterController
that has a method like this:
public function register(Request $request)
{
// Validation Data
$validData = $this->validate($request, [
'user_input' => 'required|unique:users,usr_name|unique:members,mbr_mobile|regex:/^09\d{9}$/|max:11|min:11',
]);
// sending verify sms
$sms = new SendSms(request()->all()['user_input'],43,request()->all());
$sms->send();
// submit session ?
return response([
'data' => 'An sms sent to you in order to verify',
'status' => 200
]);
}
So it simply sends a verification code to user mobile phone and now I need to verify it at another method:
public function verifyCode(Request $request)
{
DB::beginTransaction();
try {
// need the retrieved session phone number here
$check = DB::table('verify_sms')
->whereVfsVerifyCode($request->verifyCode)
->whereVfsMobileNumber(session("req")['user_input'])
->whereRaw("(UNIX_TIMESTAMP() - vfs_time) < ?", [180])
->first();
if (!empty($check)) {
$user = User::Create([
'usr_name' => session("req")["user_input"],
'usr_is_active' => 1,
]);
DB::table('verify_sms')->whereVfsId($check->vfs_id)->update(['vfs_status' => '1']);
DB::commit();
Auth::loginUsingId($user->usr_id);
return response([
'status' => 'success'
],200);
} else {
return response([
'data' => 'Something goes wrong',
'status' => 'error',
],401);
}
} catch (\Exception $e) {
dd($e);
DB::rollBack();
}
}
Now the problem here is that, I need the phone number that user had entered but don't know how to send that as session in API Controllers!
So if you know how to properly do this, please let me know...
CodePudding user response:
To answer specific question, you could use session helper and write phone number in session in register function:
public function register(Request $request)
{
// Validation Data
$validData = $this->validate($request, [
'user_input' => 'required|unique:users,usr_name|unique:members,mbr_mobile|regex:/^09\d{9}$/|max:11|min:11',
]);
session(['user_phone_number' => $request->input('user_input')]);
// rest of the code ...
}
and than retrieve it from session in verifyCode:
public function verifyCode(Request $request)
{
$user_phone_number = session('user_phone_number');
if(!$user_phone_number){
//TODO: handle missing phone number from session
}
// rest of the code
}
However, better approach would be if you make another Model / Db table "TempUser" and store user data there.
My approach would be that I would not validate phone number. I think checking "verifyCode" that was sent via sms in enough.
CodePudding user response:
After you have successfully registered, generate the token and add it to the header. The token will verify the user, so you don't need to get the mobile number, but you can get the mobile number by calling auth()->user()->mobile_phone.