我正在尝试使用Passport创建API身份验证,但在使用 createToken ()注册用户时似乎无法创建令牌。
我已经检查过我已经包含了HasApiTokens,但仍然会出现同样的错误。
错误
方法Illuminate \ Database \ Query \ Builder :: createToken不存在
应用\用户
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);
}**
}
答案 0 :(得分:4)
您需要获取用户。目前$ user是QueryBuilder,而不是用户对象。
User::where('email', $email)->where('password', $password)->first();
答案 1 :(得分:1)
您需要添加get()
或first()
或' firstOrFail()'等方法。获取数据库结果。所有where
个链都只返回QueryBuilder
个对象。第二件事是你不能将密码保存为纯文本(如果你正在保存,那么请在保存之前更改它并对其进行哈希处理)。对于你的情况,它将成为:
$user = User::where('email' , $email)->where( 'password' , $password)->first();
在哈希密码的场景中:
$user = User::where('email' , $email)->first();
if(Hash::check(optional($user)->password, $request->password)) {
// your code here
}
答案 2 :(得分:0)
您需要添加
use Laravel\Passport\HasApiTokens;
class User extends Authenticatable {
use HasApiTokens,
Notifiable;
您的用户模型的特征。