Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

OrderBy json column in laravel

I have a table which has json column named measurements , it is like this :

{
"area" : "100",
"rooms" : "2",
.
.
.
}

I tried to order by area but it does not return the correct result:

Home::where('status', 'active')->orderBy('measurements->area', 'asc')->get();

After that I used this one :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Home::query()
    ->where('status','active')
    ->orderByRaw('CAST(features->area AS unsigned)', 'asc')
    ->get();

but It returns error :

SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'area AS unsigned) limit 14 offset 0' at line 1

How can exactly order by json column? Please write code.

>Solution :

Try:

->orderByRaw('CAST(features->"$.area" AS unsigned)', 'asc')

or

->orderByRaw('CAST(JSON_EXTRACT(features, "$.area") AS unsigned)', 'asc')
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading