Laravel get rows with created_at not older than 24 hours
Asked Answered
C

1

5

I need to get all the rows on my database that meet some criteria. One those criteria is to not be older than 24 hours.

I've been trying different solutions posted on SO but none seem to work.

I've tried all this solutions:

select models that more than 24 hours have passed since their creation in laravel

Retrive records where updated_at is older than created_at with 2 hours in Laravel (eloquent)

Get rows where created date is older than 14 days

I'm getting no error and i can see on the database that I have results. This is how my query looks now:

$token = RefreshToken::where([['refresh', $refreshToken], ['valid', true], ['created_at', '<=', Carbon::now()->subDays(1)->toDateTimeString()]])->first();

Log::debug(($token));

I want to get the first token that has the refresh value that comes from a form, is valid and has been created in less than 24 hours.

Candice answered 12/5, 2022 at 14:50 Comment(0)
P
9

Less than 24 hours is:

['created_at', '>=', Carbon::now()->subHours(24)->toDateTimeString()]

With >=, not <=

Also be sure you use the same timezone when you save in DB and when you SELECT them.

Side note, 1 day is not 24 hours, (it can be 23 or 25 due to DST and even 22 and 26 in Antarctica). If you can, use UTC everywhere in your back-end.

Piassava answered 12/5, 2022 at 15:58 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.