Tags
Asked 3 years ago
17 Jun 2021
Views 203
Roy

Roy posted

orderBy on a relationship in Laravel

orderBy on a relationship in Laravel
Nilesh

Nilesh
answered Apr 27 '23 00:00

You can use the orderBy( ) method on a relationship in Laravel to order the results based on a column in the related table. Here's an example:



$users = User::with(['posts' => function ($query) {
                $query->orderBy('created_at', 'desc');
            }])
            ->get();

In this example, we are using the with() method to eager load the posts relationship for all users. We pass a closure to the with() method that defines the query for the posts relationship. Inside the closure, we use the orderBy() method to order the posts by the created_at column in descending order.

You can also use the order By() method on nested relationships by chaining the relationship method calls:



$users = User::with(['posts.comments' => function ($query) {
                $query->orderBy('created_at', 'desc');
            }])
            ->get();

In this example, we are using the with() method to eager load the posts relationship with the comments relationship nested inside it. We pass a closure to the with() method that defines the query for the posts. comments relationship. Inside the closure, we use the orderBy() method to order the comments by the created_at column in descending order.

Note that when ordering by a relationship column, you need to use the name of the relationship method instead of the name of the column in the orderBy() method. For example, if you have a user relationship on the post model, you would use orderBy ('user.name', 'asc') instead of orderBy ('user_id', 'asc') to order the posts by the name of the user who created them.
Post Answer