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();
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'); }]);
Leave a reply