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

cooperino's avatar

How can I convert these two separate but nearly identical queries

I have two queries based on some value, they are nearly identical so I feel like I can do it neater. The only difference in the query is this part:

->select(DB::raw('DATE_FORMAT(created_at, "%M-%y") as date'))

And

->select(DB::raw('DATE(created_at) as date'))

So right now I have an if-else block based on some $value

Can I remove the condition and make it same query and in a still readable way? Or any change, such as doing the condition and echo the query inline will make it worse

0 likes
6 replies
tykus's avatar
tykus
Best Answer
Level 104

Well, the format is the only difference, so

->selectRaw('DATE_FORMAT(created_at, $boolean ? "%M-%y" : "%Y-%m-%d") as date')
1 like
cooperino's avatar

@tykus I've been trying to make it work for a while but I keep getting errors, suck as A non well formed numeric value encountered or SQL syntax violation. I couldn't make the ternary expression work inside the select. I've tried yours and also:

 ->selectRaw('DATE_FORMAT(created_at,' . $boolean ? "%Y-%m" : "%Y-%m-d" .') as date)..
tykus's avatar

@cooperino is it a matter of missing quotation marks around the format string; it might be easier to see like this:

->selectRaw(
    sprintf('DATE_FORMAT(created_at, \'%s\') as date', $boolean ? "%Y-%m" : "%Y-%m-%d")
)
1 like
cooperino's avatar

@tykus yes! I eventually did something similar just with double quotes, thank you

Snapey's avatar

you could use the same query and get the date cast to an instance of Carbon then format it however you like later

1 like
cooperino's avatar

thank you guys, at first I thought I could not do the same and I have to use DATE and DATE_FORMAT separately, will give it a try now

Please or to participate in this conversation.