Home / Snippets / Laravel Eager Load Order By
Laravel Eager Load Order By cover

Laravel Eager Load Order By

2.4K

3 years ago

0 comments

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!
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