Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

cooperino's avatar

Format where clause with Carbon and check if date is in the past

Is it possible to filter where clause using Carbon and check if the date is in the past? Example: I get date of the format my and I want to check if it's in the past or not:

Model::where(Carbon::createFromFormat('my', date_field), $date->isPast());

Of course the above is incorrect, I just couldn't find the correct syntax, if possible

Will I need to use raw SQL query for that? (something with AS?)

0 likes
13 replies
tykus's avatar
Model::whereDate('date_field', '<', today())

If your granularity is months rather than days:

Model::whereDate('date_field', '<', today()->startOfMonth())
2 likes
cooperino's avatar

@tykus Ok wow it's working even though I did not specify format. Does Laravel use Carbon to check every possible format under the hood?

tykus's avatar

@cooperino

Does Laravel use Carbon to check every possible format under the hood?

No.

This is a simple query where we are asking if date_field is less that today (i.e. 2022-05-15 00:00:00)

1 like
cooperino's avatar

@tykus But my date field is not so standard, it's only 2 digit month and 2 digit years, i.e. 0522

cooperino's avatar

@tykus Update: Ok my bad, it's not working :D It just returns true always if I just use < sign but it's not correct. I just tried:

$Model::whereDate('date_field','>', today())->get();

and the date was 0622 and it didn't work (returned empty collection), I need to format the date on the fly and I guess he doesn't know this format

cooperino's avatar

@tykus string

I made a query that works, however it doesn't work when we're on the same month, even though I use >=, but if the months are different that it seem to work:

Model::where(DB::raw("(STR_TO_DATE(ex_month_year,'%m%y'))"), ">=", Carbon::now())->get();

but it doesn't work if for example the date is today's month, i.e. 0522, any idea why?

tykus's avatar

@cooperino you're not storing users' credit card information in your database; or even handling users' credit card information on your server I hope!

1 like
cooperino's avatar

@tykus I found a working query:

Model::where(DB::raw("(STR_TO_DATE(CONCAT(date_field, '01'),'%m%y%d'))"), ">=", Carbon::now()->startOfMonth())
jlrdw's avatar

@cooperino if you are talking about credit cards that's for the payment gateway to handle not you.

2 likes
cooperino's avatar

@tykus @jlrdw Not storing any CC data, the gateway does. But is it not allowed to only save expiration date (and nothing more) for if the user wants to subscribe and you need to check every month if the card is expired or not?

1 like

Please or to participate in this conversation.