问题
I am trying to create API authentication using Passport but I can not seem to create a token when a user is being registered using createToken().
I have already checked I have included HasApiTokens but still gives same error.
ERROR
Method Illuminate\Database\Query\Builder::createToken does not exist
App\User
namespace App;
use Laravel\Passport\HasApiTokens;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
use HasApiTokens, Notifiable;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'name', 'email', 'password',
];
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [
'password', 'remember_token',
];
}
SignupController
**public function userLogin(Request $request)
{
$email = $request->email;
$password = $request->password;
$user = User::where('email' , $email)->where( 'password' , $password);
if($user)
{
$token = $user->createToken('MyApp')->accessToken;
$arr = array('token' => $token, 'status' => 'isTrue', 'userId' => $data[0]->id);
//return response()->json($arr , 200);
}**
}
回答1:
You need to fetch the user. Currently $user is the QueryBuilder, not the user object.
User::where('email', $email)->where('password', $password)->first();
回答2:
You need to add the methods like get()
or first()
or 'firstOrFail()' to get the database result. all the where
chains just return the QueryBuilder
's object. Second thing is that you won't be saving the password as plain text (if you are saving so then please change it and hashed it before saving). For your case, it would become:
$user = User::where('email' , $email)->where( 'password' , $password)->first();
In the scenario of hashed password:
$user = User::where('email' , $email)->first();
if(Hash::check(optional($user)->password, $request->password)) {
// your code here
}
回答3:
You need to add the
use Laravel\Passport\HasApiTokens;
class User extends Authenticatable {
use HasApiTokens,
Notifiable;
trait to your User model.
来源:https://stackoverflow.com/questions/50200173/laravel-5-6-method-illuminate-database-query-buildercreatetoken-does-not-exist