Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call to a member function createToken() on null?

When I used the passport package , I encountered this error

Call to a member function createToken() on null

Why do I get this error?

This is my code :

$users = Users::where('Email' , $username)
              ->where( 'Password' , $password)
              ->where('UserStatus' , config('global.active'))
              ->first();

if($users) {
    $success['token'] =  $users->createToken('MyApp')->accessToken;
    return response()->json(['success' => $success], $this->successStatus);
} else {
    return response()->json(['error'=>'Unauthorised'], 401);
}
like image 620
reza baghiee Avatar asked Apr 18 '18 13:04

reza baghiee


2 Answers

$user = Auth::user(); is unnecessary and is what is causing your error.

$user = Users::where('Email' , $username)->where( 'Password' , $password)->where('UserStatus' , config('global.active'))->first();
if($user){
    $success['token'] =  $user->createToken('MyApp')->accessToken;
    return response()->json(['success' => $success], $this->successStatus);
}else{
    return response()->json(['error'=>'Unauthorised'], 401);
}
like image 110
Luis felipe De jesus Munoz Avatar answered Sep 20 '22 14:09

Luis felipe De jesus Munoz


If $users were null, there's no way that part of the control structure where createToken is getting called would be reached. I wonder if this is a red herring, and there's some middleware at work here. There are actually three instances of a method by that same name, and the namespace in your error message is notable absent there:

  • /vendor/laravel/framework/src/Illuminate/Auth/Passwords/PasswordBroker.php
  • /vendor/laravel/passport/src/ApiTokenCookieFactory.php
  • /vendor/laravel/passport/src/HasApiTokens.php

That last one is a trait being used by the User model, and is the one you're calling. But I'm wondering if that error is actually coming from one of the other two. Check your error-log, probably in /storage/logs/laravel.log, and see if there's a stack-trace that might lend a clue.

like image 39
kmuenkel Avatar answered Sep 19 '22 14:09

kmuenkel