reza baghiee
reza baghiee

Reputation: 352

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);
}

Upvotes: 10

Views: 25022

Answers (3)

r.cartojano
r.cartojano

Reputation: 11

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);
}

Upvotes: 0

kmuenkel
kmuenkel

Reputation: 2789

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.

Upvotes: 2

$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);
}

Upvotes: 5

Related Questions