Multiple Column Sorting with Laravel Query Builder
Sorting a Laravel query by multiple columns is a straightforward process that leverages the orderBy() method of Laravel's Eloquent ORM. By invoking this method multiple times, you can specify the desired sort order for each column.
For example, the following code would sort the results in descending order by the name column and ascending order by the email column:
User::orderBy('name', 'DESC') ->orderBy('email', 'ASC') ->get();
This would generate the following SQL query:
SELECT * FROM `users` ORDER BY `name` DESC, `email` ASC
Note that the order in which you call the orderBy() method determines the precedence of the sort criteria. In the example above, the results will first be sorted in descending order by the name column, and then the remaining rows will be sorted in ascending order by the email column.
You can continue invoking the orderBy() method as many times as necessary to sort the results by multiple columns. This allows you to create complex sorting queries with ease.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3