Home / Snippets / How to orderBy Eloquent Relationship in Laravel
How to orderBy Eloquent Relationship in Laravel cover

How to orderBy Eloquent Relationship in Laravel

355

3 years ago

0 comments

Defining an eloquent relationship is quite straightforward in Laravel, but you can also "order" the relation by a specific column that you explicitly define. This is important if you want to have a more structured result anytime you call the relation of your eloquent model.

Imagine you have a "posts" model that has many "comments" relation like below.
<?php

namespace App\Models;

class Post extends Model
{
  public function comments() {
    return $this->hasMany(Comment::class);
  }
}

Define the Relation
To define the comments relation "orderBy" the number of "upvoes", you can write it like below.
<?php

namespace App\Models;

class Post extends Model
{
  public function commentsByUpvotes() {
    return $this->hasMany(Comment::class)->orderBy('upvotes');
  }
}

Access the Relation
Now when you get the "comments" relation from the post instance, the result will be ordered by the "upvotes" in ascending order.
$firstPostComments = Post::find(1)->commentsByUpvotes;
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