How do you sort Laravel query builder results by multiple columns?

Mary-Kate Olsen
Release: 2024-11-09 07:19:02
Original
677 people have browsed it

How do you sort Laravel query builder results by multiple columns?

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();
Copy after login

Generated Query

The above code generates the following SQL query:

SELECT * FROM `users` ORDER BY `name` DESC, `email` ASC
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template