Check if token expired in Laravel

蓝咒 提交于 2021-02-10 12:54:31

问题


I have table tokens with columns: user_id, token, expires_at.

Example:

I have token: 12345, for me, and he expires at: 2018-06-05

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..


回答1:


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
}


来源:https://stackoverflow.com/questions/50580670/check-if-token-expired-in-laravel

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!