Home >Backend Development >PHP Tutorial >How to Sort Laravel Query Builder Results by Multiple Columns?

How to Sort Laravel Query Builder Results by Multiple Columns?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-10 04:22:02921browse

How to Sort Laravel Query Builder Results by Multiple Columns?

Sorting Laravel Query Builder Results by Multiple Columns

Sorting is a crucial aspect of data management in any programming language. In Laravel 4, you can sort the results of your database queries using the orderBy() method of the Eloquent Query Builder.

To sort your results by multiple columns, simply invoke orderBy() as many times as you need:

User::orderBy('name', 'DESC')
    ->orderBy('email', 'ASC')
    ->get();

This code will produce the following query:

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

In this query, the results will be sorted first by the name column in descending order (DESC), and then by the email column in ascending order (ASC).

This flexibility allows you to easily sort your data by any combination of columns, providing you with the control you need to efficiently organize and retrieve your database records.

The above is the detailed content of How to Sort Laravel Query Builder Results by Multiple Columns?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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