Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to Use OrderBy for Multiple Columns in Laravel?
In Laravel, you can sort query results by multiple columns using the orderBy() method chained together. This allows you to create complex sorting logic where records are first sorted by one column, then by another column for records with identical values in the first column.
Syntax
The basic syntax for ordering by multiple columns in Laravel is
Model::orderBy('column1', 'ASC/DESC')
->orderBy('column2', 'ASC/DESC')
->get();
Note: To run the examples below, ensure you have Laravel installed with a configured database connection and a Student model with corresponding database table.
Consider a students table with the following structure
CREATE TABLE students( id INTEGER NOT NULL PRIMARY KEY, name VARCHAR(50) NOT NULL, email VARCHAR(50) NOT NULL, created_at TIMESTAMP NULL, updated_at TIMESTAMP NULL, address VARCHAR(100) NOT NULL, age INTEGER NOT NULL );
Sample data in the students table
| ID | Name | Address | Age | |
|---|---|---|---|---|
| 1 | Siya Khan | siya@gmail.com | Xyz | 20 |
| 2 | Rehan Khan | rehan@gmail.com | Xyz | 18 |
| 3 | Rehan Khan | rehan@gmail.com | testing | 20 |
| 4 | Priya Singh | priya@gmail.com | test123 | 20 |
Example 1: Descending by Name, Ascending by Email
This example sorts students by name in descending order, then by email in ascending order
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Student;
class StudentController extends Controller {
public function index() {
$students = Student::orderBy('name', 'DESC')
->orderBy('email', 'ASC')
->get();
return $students;
}
}
?>
The generated SQL query
SELECT * FROM students ORDER BY name DESC, email ASC
Example 2: Multiple Ascending Order
This example demonstrates sorting by multiple columns in ascending order
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Student;
class StudentController extends Controller {
public function index() {
$students = Student::orderBy('name', 'ASC')
->orderBy('age', 'ASC')
->orderBy('email', 'ASC')
->get();
return $students;
}
}
?>
The generated SQL query
SELECT * FROM students ORDER BY name ASC, age ASC, email ASC
Alternative Method Using orderByRaw()
You can also use orderByRaw() for more complex sorting
<?php
$students = Student::orderByRaw('name DESC, age ASC, email DESC')
->get();
?>
Conclusion
Laravel's orderBy() method can be chained multiple times to sort by multiple columns. The order of chaining determines the priority first column has highest priority. Use orderByRaw() for complex sorting requirements in a single method call.
