Posts Learn Components Snippets Categories Tags Tools About
/

How to orderBy Eloquent Relationship in Laravel

Learn how to orderBy your eloquent relationship in Laravel and get the record in the right order

Created on Jul 03, 2021

335 views

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;

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

)