Sorting a Laravel Query Builder Result by Multiple Columns
When working with Laravel Eloquent, you may need to sort a query builder result by multiple columns. To achieve this, utilize the orderBy() method. This method allows you to specify multiple columns and their respective sort orders.
Example:
Consider the following scenario where you want to sort the mytable table by two columns: column1 in descending order and column2 in ascending order.
SQL Statement:
SELECT * FROM mytable ORDER BY column1 DESC, column2 ASC
Laravel Query Builder Code:
User::orderBy('name', 'DESC') ->orderBy('email', 'ASC') ->get();
This code will generate the following SQL query:
SELECT * FROM `users` ORDER BY `name` DESC, `email` ASC
The above is the detailed content of How to Sort a Laravel Query Builder Result by Multiple Columns?. For more information, please follow other related articles on the PHP Chinese website!