How Can I Sort Laravel Queries by Multiple Columns?

DDD
Release: 2024-11-11 09:46:03
Original
302 people have browsed it

How Can I Sort Laravel Queries by Multiple Columns?

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

This would generate the following SQL query:

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

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!

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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template