14

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

Kingsley Akindele
  • 311
  • 1
  • 2
  • 13
  • 1
    Why have a column where you store numbers and make it a string? Just create a migration where you update the column to be a integer and then you can order by number easier. – Collin Aug 11 '20 at 09:00
  • It should work in mysql or pg. What result do you get? – zlodes Aug 11 '20 at 09:02

3 Answers3

25

you can use orderByRaw with mysql convert

$query = Section::orderByRaw('CONVERT(section, SIGNED) desc')->get();
OMR
  • 11,736
  • 5
  • 20
  • 35
4

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') 
M Khalid Junaid
  • 63,861
  • 10
  • 90
  • 118
-2
$query->orderByRaw("section::int", "desc")->get();
OMR
  • 11,736
  • 5
  • 20
  • 35
sd077
  • 465
  • 1
  • 7
  • 25
  • 1
    While this code may answer the question, it would help OP and future readers more if you explain *why* and *how* – mousetail Jan 27 '21 at 09:24
  • It's important to add that this only works with a full query, if you want to paginate or continue to tweek your query this won't work as intended. – Jorge Peña Jun 21 '22 at 18:05