Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel - Order by as Number (int), even if column type is string

here it is:-

$query = Section::orderBy("section", "desc")->get();

section here is a column with type string yet it is having numbers in it where i want to order by those numbers thanks for your response

like image 600
Kingsley Akindele Avatar asked Dec 29 '25 01:12

Kingsley Akindele


2 Answers

you can use orderByRaw with mysql convert

$query = Section::orderByRaw('CONVERT(section, SIGNED) desc')->get();
like image 71
OMR Avatar answered Dec 30 '25 13:12

OMR


First you should use proper data types while designing schema.

For your existing schema you can tweak your order by clause to type cast your value at runtime using orderByRaw method

->orderByRaw('section * 1 desc') 
like image 29
M Khalid Junaid Avatar answered Dec 30 '25 14:12

M Khalid Junaid