Posts Learn Components Snippets Categories Tags Tools About
/

Laravel Eager Load Order By

Learn how to order by a relationship when eager loading a model.

Created on Aug 28, 2021

1268 views

In this short snippet, you will learn how to order by an eloquent eager loaded relationship.

Option 1: Always order by Column


If you always want to get the relationship ordered by a certain column then you can pass the constrain within the relationship function from the model. For example get user "posts" ordered by descending "created_at" then you can define your code below.
<?php

// from the user model
public function posts() {
  return this->hasMany(Post::class)->orderByDesc('created_at');
}

Option 2: Order by relationship on demand


If you want to order by an eager loaded relationship on-demand then you can pass in a function when defining the eager loading. The code will be like below.
<?php

User::with(['posts' => function ($query) {
    $query->orderByDesc('created_at');
}])->first();
So the code above will retrieve the first user with the post relation order by descending "created_at" column.

Option 3: Sort Eager load relationship on existing model


If you have the model instance already then you can also pass in the condition within the "load" method.
<?php

$user = User::first();

$user->load(['posts' => function ($query) {
    $query->orderByDesc('created_at');
}]);
By now you should be able to Eager Load Order By in Laravel. Thanks for reading and If you find this snippet to be helpful do share it with your friends. Cheers!

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

Load comments for Laravel Eager Load Order By

)