Posts Learn Components Snippets Categories Tags Tools About

Laravel orderBy on a Relationship Field

Learn how to order by a relationship field in Laravel using these easy steps

Created on Nov 13, 2021


To order a relationship in Laravel you can make use of the eager load syntax and pass a custom condition within the logic.

Laravel orderBy Relationship via Eager Loading method

For example, imagine having a Post model and you want to order the relationship Comment by its "ID" column in "descending" order. To write that you can write your code as follows. The "with()" method can accept a function that can receive the query of the "relationship" so from there you can write your necessary condition. Besides using "with()" method you can also use the "load" method if you already have the Eloquent Model instance.

$sortDirection = 'desc';

// 1: Using "with" method
Post::query()->with(['comments' => function ($query) use ($sortDirection) {
    $query->orderBy('id', $sortDirection);

// 2: Using "load" method
$post = Post::first();

$post->load(['comments' => function ($query) use ($sortDirection) {
    $query->orderBy('id', $sortDirection);

Laravel orderBy Condition on Model Relationship

Another way to order the relationship is like below, you can define the relationship such as "hasMany()" and then later chain it with the "orderBy()" method.

// app\Models\Post.php

public function comments()
    return $this->hasMany(Comment::class)->orderBy('column');

If you like our tutorial, do make sure to support us by being our Patreon or buy us some coffee ☕️

Load comments for Laravel orderBy on a Relationship Field