Home / Snippets / Laravel orderBy on a Relationship Field
Laravel orderBy on a Relationship Field cover

Laravel orderBy on a Relationship Field

2.2K

3 years ago

0 comments

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.
<?php

$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.
<?php

// app\Models\Post.php

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

Alaz

Week-end developer currently experimenting with web, mobile, and all things programming.

Topics:

Frontend

Resource

Average

Average

Support Us

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

Welcome to PostSrc V3

PostSrc Dark Logo

You have to login to favorite this