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.
The above is the detailed content of How Can I Sort Laravel Queries by Multiple Columns?. For more information, please follow other related articles on the PHP Chinese website!