Call to a member function createToken() on null?
Asked Answered
S

3

10

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);
}
Sanguinaria answered 18/4, 2018 at 13:6 Comment(3)
Does Auth::user()->createToken('MyApp')->accessToken gives you problem?Caskey
If $user is null it meas that it probably guest (not logged).Immortal
Just remove $user = Auth::user(); and change $users to $user`Caskey
C
5

$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);
}
Caskey answered 18/4, 2018 at 13:16 Comment(0)
F
2

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.

Form answered 18/4, 2018 at 16:54 Comment(0)
W
0

You can do other way around to make it work.

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;



public function authenticate(Request $request)
{


    // add UserStatus logic here if any

    if(Auth::attempt(['Email' => $request->username, 'Password' => $request->password], $request->remember)) 
    {

     $user = Auth::user();
     $success['token'] =  $request->user()->createToken('MyApp')->accessToken;

     return response()->json(['success' => $success], $this->successStatus);

    }
    return response()->json(['error'=>'Unauthorised'], 401);
}
Wayfarer answered 22/2, 2022 at 8:39 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.