Laravel 8: why is sorting by date in eloquent is wrong, using Carbon

Viewed 66

Possible duplicates:
Laravel: How to order date, change the date format and group by the date?
Laravel Carbon format wrong date

I created a line chart using chartjs, the chart and data fetching is working fine. However the order of the dates is wrong. It starts off with Aug 2022 instead of Jan 2022.

  • When I use the orderBy(), it shows orderBy() doesn't exists error.
  • When I use createFromFormat() of Carbon, it shows missing data error.

Why? I parsed the date with Carbon and the column type is datetime, shouldn't it be working?

enter image description here

This is my laravel collection:

$data = TrafficViolation::select('id', 'violationDateTime')
            ->get()
            ->sortBy('violationDateTime')
            ->groupBy(function($data) {
                return Carbon::parse($data['violationDateTime'])->format('M, Y');
            });
1 Answers

The orderBy() is a Query Builder method. Once you call get(), you get a Collection instance.

To order the records in your DB you need to call orderBy() first, and than get():

UPDATE: I have included the records count, and date format. You still need to order the records by the violationDateTime column

$data = User::selectRaw('COUNT(*) as violation_count, DATE_FORMAT(violationDateTime, \'%M, %Y\') as formatedDate')
            ->groupBy('formatedDate')
            ->orderBy('violationDateTime')
            ->get();

if your get a Syntax error or access violation: 1055 you need to change the stritc mode in mysql to false in /config/database.php change ['connections' => ['mysql' => ['strict' => false]]]

Related