How to Sort Laravel Query Builder Results by Multiple Columns?

Patricia Arquette
Release: 2024-11-10 04:22:02
Original
866 people have browsed it

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

This code will produce the following query:

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

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!

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