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

shiro_'s avatar

Laravel Postgres Formatted Date Month Year Error Ordering Dates

I have a database that looks like this :

sum | status  |   failure_reason      | month                    |   created_at
1.2	 |  Failed  |  AbsentSubscriber	 | JANUARY  -2022	|  2022-01-17

I want to make a graph of total costs across a specified period based on different statuses. My query is returning month/year and the total cost at that time.

Despite using order by to display data in an ascending order, my graph is quite unordered. This is how my query looks :

$delivery_failure = DB::table('partners_sms')->select(DB::raw('month, sum(sum) as y'))
                ->whereBetween('created_at', [new Carbon($start_date), new Carbon($end_date)])
                ->where('failure_reason', '=', 'DeliveryFailure')
                ->groupBy('month')
                ->orderBy('month', 'DESC')
                ->get();

I have also tried this approach with no luck:

$successNonPartner = SMSData::query()->selectRaw("to_char(created_at::timestamp, 'MONTH-YYYY') as month")
            ->whereBetween('created_at', [new Carbon($start_date), new Carbon($end_date)])
            ->where('status', '=', 'Success')
            ->groupBy('created_at')
            ->orderBy('created_at', 'DESC')
            ->get();

Any advise or recommendations on an ideal approach to format my date in month/year and order the dates will be appreciated. I am using laravel and postgres.

0 likes
4 replies
neilstee's avatar

@shiro_ Why not save your month column to a proper date format? Like 2022-01-01 (January) 2022-02-01 (Feb) and so on. So you could easily sort data

shiro_'s avatar

@neilstee I need to display the month name on the graph like January 2020 and i also need to have a filter with a specified date range. Thats why i have the month column

neilstee's avatar
neilstee
Best Answer
Level 34

@shiro_ you can do so using to_char(timestamp, 'month YYYY') as monthYear in your select.

I think it's problematic saving your date as string (January 2022) and converting it back to real dates as opposed to real dates first then converting to whatever you need.

sr57's avatar

my graph is quite unordered. This is how my query looks :

and how your results look?

It should be ordered ... but not by what you want since your months are literal.

Best way in your case should be to sort by to_char(created_at,'YYYY-MM')

1 like

Please or to participate in this conversation.