Laravel 5.6 Method Illuminate\Database\Query\Builder::createToken does not exist

痞子三分冷 提交于 2021-02-20 03:54:31

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!