Search code examples
phplaraveleloquenteloquent-relationship

Laravel orderBy on a relationship


I am looping over all comments posted by the Author of a particular post.

foreach($post->user->comments as $comment)
{
    echo "<li>" . $comment->title . " (" . $comment->post->id . ")</li>";
}

This gives me

I love this post (3)
This is a comment (5)
This is the second Comment (3)

How would I order by the post_id so that the above list is ordered as 3,3,5


Solution

  • It is possible to extend the relation with query functions:

    <?php
    public function comments()
    {
        return $this->hasMany('Comment')->orderBy('column');
    }
    

    [edit after comment]

    <?php
    class User
    {
        public function comments()
        {
            return $this->hasMany('Comment');
        }
    }
    
    class Controller
    {
        public function index()
        {
            $column = Input::get('orderBy', 'defaultColumn');
            $comments = User::find(1)->comments()->orderBy($column)->get();
    
            // use $comments in the template
        }
    }
    

    default User model + simple Controller example; when getting the list of comments, just apply the orderBy() based on Input::get(). (be sure to do some input-checking ;) )