本文介绍了检查令牌在Laravel中是否过期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有带有以下列的表令牌: user_id
, token
, expires_at
.
I have table tokens with columns: user_id
, token
, expires_at
.
示例:
对我来说,我的令牌是:12345,他的到期日期是:2018-06-05
I have token: 12345, for me, and he expires at: 2018-06-05
当我生成新令牌时,我最多生成7天.
When I generate new token, I generate up to 7 days..
如何在模型中进行检查?
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..
推荐答案
我一直按照以下方式完成类似的工作.请注意,您需要 expires_at
字段作为模型上的属性.
I've always done stuff like this the following way. Note that you need the expires_at
field as an attribute on your model.
// 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
}
这篇关于检查令牌在Laravel中是否过期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!