Press "Enter" to skip to content

Ordering with JSON in Laravel

Order of MySQL results in Laravel is very simple.

Especially with Laravel, there are many methods.

But, one more this to do is, ordering with JSON column.

Things will never be simple as this.

Even when we want to order from a relationship,

It works splendidly.

It is enough (when you have inserted data perfectly).

But, there are cases, where we mess up with integers and strings. And, the order by function has different rules of operating on them.

For example, an ’11’ comes before ‘2’ in order when it is being treated as a string.

To solve this issue, we need to raw CAST approach.

This way, even if your columns are stored as a string, they will be cast to an integer first and the function order by will get the accurate results.

Everything is awesome.