Datatables.net is a really good script to manipulate table data, with ability to order by any column by clicking on its header. But the problem is that it’s ordering by string value of that column, what if we need to order by different value of that column? Typical example is about date formats.

Imagine you have a format mm/dd/yyyy, like 04/15/2019, 03/23/2020 etc. If we click on default Datatables column to order, result will be like this:

Ascending:

Descending:

Datatables script is ordering by string value, so 01/ is earlier than 03/ – no matter the months and years after that.

So, how to make it order by proper date?

We can define an “orderable” value of every column, by putting data-order attribute on the td cell.

Before:

<td>
    {{ $book->release_date ?? '' }}
</td>

After:

<td data-order="{{ \Carbon\Carbon::createFromFormat('m/d/Y', $book->release_date)->format('Y-m-d') }}">
    {{ $book->release_date ?? '' }}
</td>

Then, ordering will be correct:

You can read more about data-order attribute in the official Datatables.net documentation.

Please note that it wouldn’t work with Server-side Datatables, or, in our QuickAdminPanel, with AJAX Datatables module. Then custom ordering solution is much more complicated, read here.