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

Limited Time Offer!

For Less Than the Cost of a Starbucks Coffee, Access All DevOpsSchool Videos on YouTube Unlimitedly.
Master DevOps, SRE, DevSecOps Skills!

Enroll Now

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();
 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;
            }

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
()
x