Posts Learn Components new Snippets new Categories Tags About Device Beast sponsor
/

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

20 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;

Snippets by

PostSrc poster

PostSrc

Full stack developer mainly focusing on the front end side of the web. The main author of PostSrc and loves writing tutorial and guides online.

new

PostSrc Code Components

Collection of Tailwind CSS components for everyone to use. Browse all of the components that are right for your project.

View Components

Other Code Snippets

More