How to order the results of related models in Laravel Eloquent?

Laravel Eloquent provides the orderBy() method to sort query results from related models. This method allows you to order data from single tables or joined relationships efficiently.

Database Setup

Let's work with two related tables users and user_roles:

Users Table id | name | email 1 | Alice | alice@test.com 2 | Bob | bob@test.com 3 | Charlie | charlie@test.com User Roles Table id | user_id | role 1 | 1 | admin 2 | 2 | user 3 | 3 | moderator

Basic OrderBy Usage

Order users by name in ascending order

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\User;

class UserController extends Controller
{
    public function index()
    {
        $users = User::orderBy('name', 'ASC')->take(10)->get();
        
        foreach ($users as $user) {
            echo $user->name . "<br/>";
        }
    }
}
?>
Alice
Bob
Charlie

Ordering with Table Joins

Order results when joining related tables

<?php
namespace App\Http\Controllers;
use App\Models\User;

class UserController extends Controller
{
    public function index()
    {
        $users = User::join('user_roles', 'users.id', '=', 'user_roles.user_id')
            ->orderBy('users.name', 'ASC')
            ->select('users.*')
            ->get();
            
        foreach ($users as $user) {
            echo $user->name . "<br/>";
        }
    }
}
?>

Descending Order Examples

Order by ID in descending order

<?php
$users = User::orderBy('id', 'DESC')->take(10)->get();

foreach ($users as $user) {
    echo $user->name . " (ID: " . $user->id . ")<br/>";
}
?>
Charlie (ID: 3)
Bob (ID: 2)
Alice (ID: 1)

Multiple Column Ordering

You can chain multiple orderBy() methods for complex sorting

<?php
$users = User::orderBy('role', 'ASC')
    ->orderBy('name', 'DESC')
    ->get();
?>

Conclusion

Laravel's orderBy() method provides flexible sorting for both single tables and joined relationships. Use proper table prefixes when joining tables and chain multiple orderBy() calls for complex sorting requirements.

Updated on: 2026-03-15T10:09:54+05:30

550 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements