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

johndoee's avatar

How can order by database query from lower value to greater value in laravel

I make query orderby from lower value to greater value. Although I orderBy ASC this is not get as require

Price 	Amount 	Total
1 	4 	3
10 	4 	3
2 	2 	1
5 	2 	1
5 	4 	3
9 	4 	3


I think it need to adjust in double or triple digit when 1, 2, 3, 4, 5, / it make correct ascending but when two digit enter , cannot ascending order.

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


how can I fix this


public function buyshow(){

    $buydata = Buy :: orderBy ('price','ASC')->get();
    
       return response()->json([
        'buydata' => $buydata,
       ]);
   }
0 likes
4 replies
Tray2's avatar

You are using an alphanumerical sort, you need to use a natural sort.

What is the column type for price?

1 like
johndoee's avatar

@Tray2 need to change migration

 Schema::create('buys', function (Blueprint $table) {
            $table->id();
            $table->string('price');
            $table->string('amount');
            $table->string('total');
            $table->timestamps();
        });

what data type should change in price column

Tray2's avatar

@zwarkyaw The price should either be an integer and you store the price in cents (250) or be a decimal type and you store in dollars and cents ($2.5). They all should be stored as integer or decimal.

1 like
tykus's avatar
tykus
Best Answer
Level 104

What is the type of the price column - it is sorting like a VARCHAR or TEXT column type?

You can cast the value as INT in a raw statement, but better to have the appropriate type in the first instance!

Untested, but this should work:

$buydata = Buy::orderByRaw('CAST(price AS UNSIGNED) ASC')->get();
1 like

Please or to participate in this conversation.