Laravel orderBy on a relationship
In Laravel, you can use the orderBy
method on a relationship to sort the results of the relationship by a given column. Here's an example of how you might use orderBy
on a relationship in a Laravel application:
// Retrieve the posts that belong to a particular user, sorted by the title of the post
$user = App\User::find(1);
$posts = $user->posts()->orderBy('title', 'asc')->get();
Watch a video course
Learn object oriented PHP
This will retrieve all of the posts that belong to the user with an ID of 1, and it will sort the posts by their title in ascending order. You can also use the desc
option to sort the posts in descending order:
$posts = $user->posts()->orderBy('title', 'desc')->get();
Keep in mind that the orderBy
method should be called on the relationship itself, rather than on the resulting collection of posts. This is because the orderBy
method is defined on the relationship and not on the collection of posts.