Laravel 6:调用未定义的方法 App\\User::createToken()

Laravel 6: Call to undefined method App\\User::createToken()

我正在尝试生成令牌以通过以下方式在我的控制器中对用户进行身份验证:

namespace App\Http\Controllers\API;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Http\Request;

use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
use App\Models\User;

class AuthController extends Controller
{
    public function login()
    {
        if (Auth::attempt(['email' => request('email'), 'password' => request('password')])) {
            $user = Auth::user();


            $success['token'] = $user->createToken('myApp')->accessToken;
            dd($success['token']);

        }
    }

目前,我只是想打印出令牌。这是我的用户模型:

<?php

namespace App\Models;

use Illuminate\Notifications\Notifiable;
//use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Support\Facades\Hash;
use Laravel\Passport\HasApiTokens;

class User extends Authenticatable
{
    use HasApiTokens, Notifiable;

    const USER_FIRST_NAME_FIELD        = "first_name";
    const USER_LAST_NAME_FIELD         = "last_name";
    const USER_PREFERRED_NAME_FIELD    = "preferred_name";
    const USER_EMAIL_FIELD             = "email";
    const USER_EMAIL_VERIFIED_AT_FIELD = "email_verified_at";
    const USER_PASSWORD_FIELD          = "password";
    const USER_REMEMBER_TOKEN_FIELD    = "remember_token";
    const USER_RECEIVE_NEWSLETTER_FIELD= "receive_newsletter";
    const USER_ACTIVE_FIELD            = "active";

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        self::USER_FIRST_NAME_FIELD, 
        self::USER_LAST_NAME_FIELD,
        self::USER_PREFERRED_NAME_FIELD,
        self::USER_EMAIL_FIELD,
        self::USER_PASSWORD_FIELD,
        self::USER_RECEIVE_NEWSLETTER_FIELD,
        self::USER_ACTIVE_FIELD,
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        self::USER_PASSWORD_FIELD,
        self::USER_REMEMBER_TOKEN_FIELD
    ];

    /**
     * Automatically creates password hash when password is submitted
     *
     * @param string $password
     * @return void
     */
    public function setPasswordAttribute(string $password) : void
    {
        $this->attributes['password'] = Hash::make($password);    
    }
}

如您所见,我正在使用 HasApiTokens, Notifiable 特征,但我从我的控制器中收到一条错误消息:

Call to undefined method App\User::createToken()

Passport 已正确安装和配置。

这里有些奇怪:

注册用户时(我使用的是单独的控制器,同时也使用服务)成功创建令牌:

这是我的控制器:

<?php

namespace App\Http\Controllers\API;

use App\Services\UserService;
use Illuminate\Http\JsonResponse;
use App\Http\Controllers\Controller;
use App\Http\Requests\RegisterUserRequest;


class UserController extends Controller 
{
    private $user;

    public function __construct(UserService $user)
    {
        $this->user = $user;
    }

    public function store(RegisterUserRequest $request) : JsonResponse
    {
        // TODO: verify message on error

        $user = $this->user->register($request->validated());
        $token = $user->createToken('MyApp')->accessToken;
        dd($token);

        return response()->json(['status' => 201, 'user_id' => $user->id]);
    }

}

这是我的服务:

<?php

namespace App\Services;

use App\Models\User;
use App\Services\BaseServiceInterface;

class UserService implements BaseServiceInterface
{

    public function register(array $formValues) : User
    {
        // 'terms and conditions' should not be saved into the db, hence it's removed
        unset($formValues['terms_conditions']);
        return User::create($formValues);
    }

}

这又是我的模型:

<?php

namespace App\Models;

use Illuminate\Notifications\Notifiable;
//use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Support\Facades\Hash;
use Laravel\Passport\HasApiTokens;

class User extends Authenticatable
{
    use HasApiTokens, Notifiable;

    const USER_FIRST_NAME_FIELD        = "first_name";
    const USER_LAST_NAME_FIELD         = "last_name";
    const USER_PREFERRED_NAME_FIELD    = "preferred_name";
    const USER_EMAIL_FIELD             = "email";
    const USER_EMAIL_VERIFIED_AT_FIELD = "email_verified_at";
    const USER_PASSWORD_FIELD          = "password";
    const USER_REMEMBER_TOKEN_FIELD    = "remember_token";
    const USER_RECEIVE_NEWSLETTER_FIELD= "receive_newsletter";
    const USER_ACTIVE_FIELD            = "active";

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        self::USER_FIRST_NAME_FIELD, 
        self::USER_LAST_NAME_FIELD,
        self::USER_PREFERRED_NAME_FIELD,
        self::USER_EMAIL_FIELD,
        self::USER_PASSWORD_FIELD,
        self::USER_RECEIVE_NEWSLETTER_FIELD,
        self::USER_ACTIVE_FIELD,
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        self::USER_PASSWORD_FIELD,
        self::USER_REMEMBER_TOKEN_FIELD
    ];

正如我告诉您的,创建用户时,令牌已正确生成。

我会说 Auth::user() 没有直接调用我的模型,但我不确定这是怎么回事。

知道为什么吗? 谢谢

所以,这不是正确的方法,但目前有效:

<?php

namespace App\Http\Controllers\API;

use App\Models\User;
use Illuminate\Support\Facades\Auth;
use App\Http\Controllers\API\BaseController;

class AuthController extends BaseController
{
    public function login()
    {
        if (Auth::attempt(['email' => request('email'), 'password' => request('password')])) {
            $authenticated_user = \Auth::user();
            $user = User::find($authenticated_user->id);
            dd($user->createToken('myApp')->accessToken);
        }

        dd('here');
    }
}

现在我看到了令牌。

我想以正确的方式做到这一点,所以如果有人能帮助我,我将不胜感激。 谢谢

由于您的守卫返回了错误的 User 模型,App\User,您应该检查您的身份验证配置,'config/auth.php'。在 providers 数组中,将使用 App\User 模型的任何提供商(通常是 users 调整为 App\Models\User

'providers' => [
    'users' => [
        'driver' => 'eloquent',
        // 'model' => App\User::class,
        'model' => App\Models\User::class,
    ],
    ...
],

您可以让 auth.basic 中间件为您进行身份验证,方法是在构造方法中调用它:

public function __construct()
    {
        $this->middleware('auth.basic'); 
    }

然后为当前认证用户生成访问令牌,return用户信息连同访问令牌:

public function login()
    {
        $Accesstoken = Auth::user()->createToken('Access Token')->accessToken;

        return Response(['User' => Auth::user(), 'Access Token' => $Accesstoken]);
    }

现在控制器看起来像这样:

    <?php


namespace App\Http\Controllers\API;

use App\Models\User;
use Illuminate\Support\Facades\Auth;
use App\Http\Controllers\API\BaseController;

class AuthController extends BaseController
{
        /**
         * Instantiate a new controller instance.
         *
         * @return void
         */
        public function __construct()
        {
            $this->middleware('auth.basic'); 
        }

        public function login()
        {
            $Accesstoken = Auth::user()->createToken('Access Token')->accessToken;

            return Response(['User' => Auth::user(), 'Access Token' => $Accesstoken]);
        }
    }

就我而言,我错过了使用 Trait HasApiTokens 这就是 laravel 无法创建令牌的原因。

刚刚打开User.php

after name space include

use Laravel\Passport\HasApiTokens;

然后里面 class

use HasApiTokens

请注意:我正在使用 laravel 7。