**我想在 laravel 10 中进行身份验证,但出现错误:错误:调用未定义的方法 Illuminate\Auth\GenericUser::createToken() **
我的用户模型是 UserRoot :
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class UserRoot extends Model {
use HasFactory;
}
控制器:
<?php
namespace App\Http\Controllers\Api;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Http\Requests\UserRequest;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Validator;
class UserRoot extends Controller {
public function login(UserRequest $request){
$credentials = $request->validated();
if (!Auth::attempt($credentials)) {
return response([
"msg"=>"Not connected"
]);
} else {
$user = Auth::user();
$token = $user->createToken("mytoken")->plainTextToken;
return response([
"msg"=>"connected",
"user"=>Auth()->user(),
"status"=>"ok",
"token"=>$token
]);
};
}
}
auth.php
:
providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\Models\User::class,
],
'users' => [
'driver' => 'database',
'table' => 'user_roots',
],
],
请帮我解决这个问题。
您遇到的错误是因为您的
UserRoot
模型没有使用正确的身份验证特征,并且没有从正确的基类继承。为了使 Laravel 的身份验证和令牌生成正常工作,您需要使用 Authenticatable
基类和 HasApiTokens
特征。
以下是修改您的
UserRoot
模型的方法:
<?php
namespace App\Models;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Laravel\Sanctum\HasApiTokens;
class UserRoot extends Authenticatable
{
use HasFactory, HasApiTokens;
protected $fillable = [
'name',
'email',
'password'
];
protected $hidden = [
'password',
'remember_token'
];
}
确保您的迁移遵循正确的模型名称命名约定;
此外,在您的
config/auth.php
中,您应该更新用户提供程序以指向您的新 UserRoot
模型:
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\Models\UserRoot::class,
],
],
接下来确保您安装了 Laravel Sanctum。如果没有,请通过 Composer 安装:
composer require laravel/sanctum
并发布其配置:
php artisan vendor:publish --provider="Laravel\Sanctum\SanctumServiceProvider"
这应该可以解决
createToken()
方法未找到错误,并允许您生成用于身份验证的令牌。