检查 Laravel 中的令牌是否过期
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/50580670/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Check if token expired in Laravel
提问by Dumitru
I have table tokens with columns: user_id
, token
, expires_at
.
我有带有列的表标记:user_id
, token
, expires_at
。
Example:
例子:
I have token: 12345, for me, and he expires at: 2018-06-05
我有令牌:12345,对我来说,他在:2018-06-05 到期
When I generate new token, I generate up to 7 days..
当我生成新令牌时,我最多生成 7 天..
How I can check this in model?
我如何在模型中检查这个?
I tryied do with scope in model:
我尝试使用模型中的范围:
public function scopeExpired($query) {
return $this->where('expires_at', '<=', Carbon::now())->exists();
}
But not working. Always false..
但不工作。总是假的。。
回答by Loek
I've always done stuff like this the following way. Note that you need the expires_at
field as an attribute on your model.
我总是用以下方式做这样的事情。请注意,您需要将该expires_at
字段作为模型的属性。
// Probably on the user model, but pick wherever the data is
public function tokenExpired()
{
if (Carbon::parse($this->attributes['expires_at']) < Carbon::now()) {
return true;
}
return false;
}
Then from wherever you can call:
然后从任何你可以打电话的地方:
$validToken = $user->tokenExpired();
// Or realistically
if ($user->tokenExpired()) {
// Do something
}