Reputation: 512
I have an expired_at
column in database; that when creating any row, by default will be 5 minutes future of the creation time, and i want exclude rows which their expired_at
has passed (littler from current time).
For example i have this rows in games
table:
id creator_id created_at updated_at expire_at
1 123456789 2017-04-26 01:13:22 2017-04-26 01:13:22 2017-04-26 01:18:22
2 234567890 2017-04-26 01:16:06 2017-04-26 01:16:06 2017-04-26 01:21:06
And when i fetch all rows with Game::all()
or Game::where('condition')
function at time 01:19:30
, row 1 shouldn't be fetched, but row 2 should, because it still not expired.
I don't want to process expire time in target code, but in model code (for example overriding where function in model class)
Upvotes: 1
Views: 513
Reputation: 5083
You can achieve this my the means of a (global) scope.
See also this link.
protected static function boot()
{
parent::boot();
static::addGlobalScope('not_expired', function (Builder $builder) {
$builder->where('expired_at', '>', Carbon::now());
});
}
Global scopes will be applied to all queries except when you disable them specifically.
Disabling them can be done by:
Game::withoutGlobalScope('not_expired')->all();
Upvotes: 2