未定义的索引:App\LoginToken {"userId":3,"exception":"[object] Laravel 8



我正在尝试从模型AppLoginToken创建一个LoginToken

在使用Laravel 5.6之前

我已经升级到8,它停止工作了。

我已经尝试寻找我正在做的语法错误,但我无法解决它

这是AppLoginToken.php的代码

namespace App;
use IlluminateDatabaseEloquentModel;
use CarbonCarbon;
use Hash;
class LoginToken extends Model
{
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'id',
'user_id',
'creating_user',
'token_hash',
'expires_at',
];
//Only available during the request the token was created in
private $token;

public static function boot() {
self::creating(function($loginToken)
{
$loginToken->identifier = str_random(10);
$loginToken->token = str_random(30);
$loginToken->token_hash = bcrypt($loginToken->token);
});
}
public function user() 
{    
return $this->belongsTo(AppUser::class);
}
public static function findValidToken($token)
{
$id = explode('_', $token)[0];
$key = explode('_', $token)[1];
$foundToken = static::where(['identifier' => $id])
->where('expires_at', '>', new Carbon())
->first();
if(Hash::check($key, $foundToken->token_hash)) {
return $foundToken;
}
return false;
}
public function getToken()
{
return $this->identifier . '_' . $this->token;
}
}

App User.phpLoginToken模型上带有HasMany的用户模型

public function loginTokens()
{
return $this->hasMany(AppLoginToken::class);
}

这里我从TokenController

访问它
use AppLoginToken;
$data = json_decode($request->getContent(), true);
$required_parameters = [
'email',
];
if ($this->error_missing_parameter($data, $required_parameters)) {
return $this->error_missing_parameter($data, $required_parameters);
}
$user = User::where('email', $data['email'])->first();
if (!$user) {
return response()->json([
'status' => 'not_found',
'found' => 'false',
], 200);
}
$loginToken = User::loginTokens()->create([
'creating_user' => IlluminateSupportFacadesAuth::user()->id,
'expires_at' => new Carbon('+5 minutes'),
]);

Error.log

[2021-03-15 05:59:46] development.ERROR: Non-static method AppUser::loginTokens() should not be called statically {"userId":3,"exception":"[object] (ErrorException(code: 0): Non-static method App\User::loginTokens() should not be called statically at C:\laragon\www\TurboPassPoiBetaC\app\Http\Controllers\API\LoginTokensController.php:51)

您忘记在TokenController中创建User model的实例了。loginTokens()方法不是一个静态函数,所以我认为你应该首先创建一个用户模型的实例。应该像下面这样

// Attention this line.
$user = new User();
$loginToken = $user->loginTokens()->create([
'creating_user' => IlluminateSupportFacadesAuth::user()->id,
'expires_at' => new Carbon('+5 minutes'),
]);

相关内容

  • 没有找到相关文章

最新更新