gpt4 book ai didi

laravel-8 - Laravel Sanctum token ()未定义

转载 作者:行者123 更新时间:2023-12-05 02:43:18 25 4
gpt4 key购买 nike

我是 laravel 的新手,正在尝试使用 sanctum 为登录构建一个 api。

我遵循了文档和一些教程,但我遇到了一个错误,即即使使用 HasApiToken,我的用户类也无法访问 token 函数。

这是我的用户模型:

<?php

namespace App\Models;

use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;

class User extends Authenticatable
{
use HasApiTokens, HasFactory, Notifiable;

/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'name',
'email',
'password',
'alt_id',
'country_id',
'birth'
];

/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [
'type',
'password',
'remember_token',
];

/**
* The attributes that should be cast to native types.
*
* @var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];

public function country()
{
return $this->hasOne(Country::class);
}
}

[这是错误信息][1][1]: /image/QzGK9.png

我也已经检查了 config/auth.php 中的路由,它是 App\Models\User::class

最佳答案

我通过将 $user->tokens()->delete(); 添加到我的 AuthController@logout 中解决了这个问题,

 <?php

namespace App\Http\Controllers;

use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;

class AuthController extends Controller
{
public function logout(User $user){

$user->tokens()->delete();

return [
'message' => 'Logged out'
];
}
}

用户模型看起来像这样。

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;

class User extends Authenticatable
{
use HasApiTokens, HasFactory, Notifiable;

protected $fillable = [
//some code
];
protected $hidden = [
//some code
];
protected $casts = [
//some code
];
}

关于laravel-8 - Laravel Sanctum token ()未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66979272/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com