Tags
Asked 2 years ago
17 Jun 2021
Views 164
Brannon

Brannon posted

How to Use Order By for Multiple Columns in Laravel 4?

How to Use Order By for Multiple Columns in Laravel 4?
iPhone-coder

iPhone-coder
answered Apr 27 '23 00:00

In Laravel 4, you can use the orderBy() method to order the results of a query by multiple columns. Here's an example:



$users = DB::table('users')
            ->orderBy('last_name', 'asc')
            ->orderBy('first_name', 'asc')
            ->get();

In this example, we build a query using the Laravel query builder that selects all users from the users table and orders the results by the last_name column in ascending order, and then by the first_name column in ascending order.

The orderBy() method takes two arguments: the name of the column to order by, and the direction to order the results (asc for ascending order or desc for descending order). You can call orderBy() multiple times to order the results by multiple columns.

Note that the orderBy() method modifies the query builder instance and does not execute the query. To execute the query and retrieve the results, you need to call one of the query execution methods like get(), first(), or paginate().
Post Answer