Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

muzafferdede's avatar

Ordering number result with alphabet order.

Hello,

I am trying to list a result with alphabet ordered numbers for a pizza shop project. Pizza names are using number names instead of letters names. So instead of saying "cheese pizza", will gonna use pizza no 1. type of names. so when i use this in my PizzaController;

$pizzas = Pizza::orderBy('name','asc')->get();

the result is like:

1,10,2,3,4,5,6,7,8,9

what i am trying to come out is:

1,2,3,4,5,6,7,8,9,10,11..etc..

anyone can help?

Thanks.

0 likes
10 replies
WebKenth's avatar
WebKenth
Best Answer
Level 16

It's because your name attribute in your table is of the var_char

which contains all letters and numbers so it looks at the first character in each string and sorts it

Solution: make it an integer

Off Topic: why not have both a number and a name attribute?

4 likes
muzafferdede's avatar

@WebKenth :

i use integer in table.

$table->integer('name')->unique();

@tisuchi :

i get this error with that:

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'LENGTH(name)' in 'order clause' (SQL: select * from pizzas order by LENGTH(name) asc, name asc)

muzafferdede's avatar

@WebKenth you are right. I just double check my database, somehow even i set integer in my migration it was varchar in database. once i correct it to integer in database, the result is fixed. Thank you :)

tisuchi's avatar

May be you can try this than-

->orderByRaw('LENGTH(name) asc')
1 like
WebKenth's avatar

@lexionlu if my comment answered your question, be sure to mark it as an answer so others can quickly find the correct answer :)

muzafferdede's avatar

@tisuchi your solution works as well once i correct with

->orderByRaw('LENGTH(name) asc')

Thanks. :)

gofind's avatar

$pizzas = Pizza::all()->sortBy("name");

gerritsevilla's avatar

Order the resulting collection

$unorderedThings = Thing::orderBy('id')->get();
$orderedThings = $unorderedThings->sort();

Please or to participate in this conversation.