0

This issue is happening across the entire application...

I have datatables & charts:

  1. Datatables don't sort by dateTime correctly, aka Started Column.

enter image description here

  1. Charts always starts with the latest date...not by order:

enter image description here

I am using Carbon for datatables like this:

->editColumn('startDateTime', function ($report) {
   return Carbon::parse($report->startDateTime)->format('d M, Y');
})

For the charts, returning data as json then format the date:

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

The column type of these dates are DateTime in the database.

What's frustrating is that there is a datatable called Audit Log that came with the theme (Metronic 8) and it's sorting the date correctly here (created at):

enter image description here

And looking to its controller:

->editColumn('created_at', function (Activity $model) {
    return $model->created_at->format('d M, Y H:i:s');
})

Looking at the Model there isn't anything related to Carbon or date functions there, noting that the data type of created_at is timestamp.

I tried:

  • Changing data type to timestamp instead of datetime.
  • Copying the same code of audit log, no need for Carbon, I get an error format() unknown.
Abdulrahman Mushref
  • 1,012
  • 2
  • 18
  • 40

1 Answers1

0

To me it looks like you are overcomplicating things, why don't you just sortByDesc if you need the newest results first I do not understand. You can do this like so:

First in you TrafficValidation model add a casts to datetime

protected $casts = [
    'violationDateTime' => 'datetime',
];

Then where you return the query just do

$data = TrafficViolation::select('id', 'violationDateTime')
        ->orderByDesc('violationDateTime')
        ->get()
        ->groupBy(function($data) {
            return Carbon::parse($data->violationDateTime)->format('M');
        });

And the reason audit log works for sorting is because it by default doesnt look at all at your query sorting, it takes the data and sorts it by itself

dz0nika
  • 882
  • 1
  • 5
  • 16
  • Nice, but when I use plain ```format()``` without Carbon I get 500 server error...```Failed to load resources``` And whatever types of sorting, it always starts with August: https://snipboard.io/rY3eSK.jpg – Abdulrahman Mushref Aug 10 '22 at 09:45