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.
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:
Example of using the "orderBy" method on a relationship to sort the results of the relationship by a given column in Laravel
// 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();
<div class="alert alert-info flex not-prose">![]()
<span class="hidden md:block">Watch a video course</span>Learn object oriented PHP</div>
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:
Example of using the "desc" option to sort the items in descending order in Laravel
$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.