Dumitru
Dumitru

Reputation: 2183

Check if token expired in Laravel

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

Upvotes: 2

Views: 20481

Answers (1)

Loek
Loek

Reputation: 4135

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
}

Upvotes: 7

Related Questions