Failure to create Laravel Sanctum token after user has been registered using a One Time Pin (OTP)

I am trying to create a login token for a user after they register on my application and have verified their mobile device using an OTP sent via sms. The problem is that, when a user logs in, the token is created perfectly. However, when I try to create this token on registration, no token is generated. When a user registers, I want to immediately log them into my app.

Note: This is an app using an API. The login logic works perfectly.

Question Is there anywhere I might be missing it. Have been debugging but no success.

<?php

namespace App\Http\Controllers\Admin;

use App\Models\User;
use App\Exceptions\Handler;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Validator;
use App\Http\Resources\LoginResource;

class RegisterController extends Controller
{
   
    public function verifyOTP(Request $request){

        $validate = Validator::make($request->all(), [
            'otp' =>'required|digits:4',
            'cellphone' =>'required|digits:10',
        ]);

        if ($validate->fails()){
            return response($validate->errors(), 400);
        }
        
        $user = DB::table('users')
                    ->where('cellphone', $request->cellphone)
                    ->where('otp', $request->otp)
                    ->first();

            if( !$user ){
                return response('Wrong OTP. Try again.', 400);
            }else{

            $updatedUser = DB::table('users')
                            ->where('cellphone', $request->cellphone)
                            ->update([
                                'status' => 1,
                                'otp' => NULL,
                                'account_verified' => 1,
                            ]);

            //allocate the user with an authentication token
            $loggedInUser = new LoginResource($user);

            /******THE FOLLOWING LINE IS THE ONE WITH THE PROBLEM WHERE THE TOKEN IS NOT BEING CREATED. SAYS UNDEFINED METHOD createToken******/
            $token = $user->createToken('registration-login-token');
                
            return response([
                    'user'  =>  $loggedInUser,
                    'token' =>  $token->plainTextToken,
                ], 200);
        }
}

}

The error i get is
Error: Call to undefined method stdClass::createToken() in file .../app/Http/Controllers/Admin/RegisterController.php on line 78

>Solution :

Instead of DB you have to use Eloquent Model so use User model instead of DB in below Query :

$user = DB::table('users')
                    ->where('cellphone', $request->cellphone)
                    ->where('otp', $request->otp)
                    ->first();

Leave a Reply