How to order in Laravel high to low, low to high products – by price with this code?

DevOps

MOTOSHARE 🚗🏍️
Turning Idle Vehicles into Shared Rides & Earnings

From Idle to Income. From Parked to Purpose.
Earn by Sharing, Ride by Renting.
Where Owners Earn, Riders Move.
Owners Earn. Riders Move. Motoshare Connects.

With Motoshare, every parked vehicle finds a purpose. Owners earn. Renters ride.
🚀 Everyone wins.

Start Your Journey with Motoshare

To order products in Laravel by price in either high to low or low to high, you can use the orderBy the method provided by Laravel’s query builder.

Here is an example code snippet that you can use to order products in Laravel by price in descending or ascending order:

// To get products in descending order by price
$products = DB::table('products')
               ->orderBy('price', 'desc')
               ->get();

// To get products in ascending order by price
$products = DB::table('products')
               ->orderBy('price', 'asc')
               ->get();
Code language: PHP (php)
 switch ($sortBy) {
                case 'total_cost':
                    if (isset($sortOrder) && ($sortOrder == 'ASC' || $sortOrder == 'DESC')) {
                        $quoteBids = $quoteBids->orderBy('quote_bids.total_cost', $sortOrder)->paginate(10);
                    } else {
                        $response = [
                            'success' => false,
                            'data' => 'Validation Error.',
                            'message' => 'sortOrder1111 request param is not ASC or DESC'
                        ];
                        return response()->json($response, 404);
                    }
                    break;
                
                default:
                    $quoteBids = $quoteBids->orderBy('quote_bids.total_cost', 'ASC')->paginate(10);
                    break;
            }Code language: PHP (php)

In the above code snippet, we are using Laravel’s DB facade to perform a database query to fetch products from the products table. We are then using the orderBy method to order the products by their price column in either descending (desc) or ascending (asc) order.

You can replace the DB::table('products') with your own Eloquent model if you are using Eloquent to interact with your database.

Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x