Multi-Column Sorting with orderBy() in Laravel Query Builder
When working with Eloquent in Laravel, you may encounter scenarios where you need to sort query results based on multiple criteria. This article demonstrates how to effectively sort a query builder result by multiple columns.
Multiple orderBy() Method Invocations
To sort by multiple columns, you can utilize the orderBy() method as many times as necessary. Each invocation defines an additional sorting criteria. For example:
$users = User::orderBy('name', 'DESC') ->orderBy('email', 'ASC') ->get();
Generated Query
The above code generates the following SQL query:
SELECT * FROM `users` ORDER BY `name` DESC, `email` ASC
This query sorts the users table in descending order by the name column and then in ascending order by the email column.
Conclusion
By chaining multiple orderBy() method calls, you can conveniently sort Laravel query builder results based on any combination of columns. This provides flexibility in managing and retrieving data from your database tables.
The above is the detailed content of How do you sort Laravel query builder results by multiple columns?. For more information, please follow other related articles on the PHP Chinese website!