Laravel 8 中的未定义类型 Laravel\Sanctum\HasApiTokens

Undefined type Laravel\Sanctum\HasApiTokens in Laravel 8

需要有人帮我解决这个问题。 Laravel Sanctum

我已经在我的本地服务器上安装了基本的默认 laravel 8++。

我按照LaravelSanctum的指示。但我坚持要获取 HasApiTokens

1. composer require laravel/sanctum
2. php artisan vendor:publish --provider="Laravel\Sanctum\SanctumServiceProvider"
3. php artisan migrate

我添加我的 kernel.php 如下所示

use Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful;

'api' => [
    EnsureFrontendRequestsAreStateful::class,
    'throttle:api',
    \Illuminate\Routing\Middleware\SubstituteBindings::class,
],

然后在 config>auth.php 中,我将驱动程序更改为 'sanctum'

 'guards' => [
        'web' => [
            'driver' => 'session',
            'provider' => 'users',
        ],

        'api' => [
            'driver' => 'sanctum',
            'provider' => 'users',
            'hash' => false,
        ], 
    ],

这是我的 composer.json

{
    "name": "laravel/laravel",
    "type": "project",
    "description": "The Laravel Framework.",
    "keywords": [
        "framework",
        "laravel"
    ],
    "license": "MIT",
    "require": {
        "php": "^7.3|^8.0",
        "fideloper/proxy": "^4.4",
        "fruitcake/laravel-cors": "^2.0",
        "guzzlehttp/guzzle": "^7.2",
        "laravel/framework": "^8.12",
        "laravel/passport": "^10.1",
        "laravel/sanctum": "^2.9",
        "laravel/tinker": "^2.5",
        "symfony/psr-http-message-bridge": "^2.0"
    },
    "require-dev": {
        "facade/ignition": "^2.5",
        "fakerphp/faker": "^1.9.1",
        "laravel/sail": "^1.0.1",
        "mockery/mockery": "^1.4.2",
        "nunomaduro/collision": "^5.0",
        "phpunit/phpunit": "^9.3.3"
    },
    "config": {
        "optimize-autoloader": true,
        "preferred-install": "dist",
        "sort-packages": true
    },
    "extra": {
        "laravel": {
            "dont-discover": []
        }
    },
    "autoload": {
        "psr-4": {
            "App\": "app/",
            "Database\Factories\": "database/factories/",
            "Database\Seeders\": "database/seeders/"
        }
    },
    "autoload-dev": {
        "psr-4": {
            "Tests\": "tests/"
        }
    },
    "minimum-stability": "dev",
    "prefer-stable": true,
    "scripts": {
        "post-autoload-dump": [
            "Illuminate\Foundation\ComposerScripts::postAutoloadDump",
            "@php artisan package:discover --ansi"
        ],
        "post-root-package-install": [
            "@php -r \"file_exists('.env') || copy('.env.example', '.env');\""
        ],
        "post-create-project-cmd": [
            "@php artisan key:generate --ansi"
        ]
    }
}

但是当我尝试 import/use Laravel/Sanctum/HasApiTokens 时,它显示“未定义类型”。图片如下

这是另一个屏幕截图。在 Laravel.

之后没有任何 sanctum 目录

我想 SanctumServiceProvider 不会自动注册到您的应用程序中。要解决您的问题,您应该在 config/app.php.

中手动添加服务提供商
'providers' => [
    //...
    Laravel\Sanctum\SanctumServiceProvider::class,
]; 

只需关闭并重新打开 vscode