Sorting data with Eloquent Sorting data with Eloquent laravel laravel

Sorting data with Eloquent


I just ran into the same problem on a project I am developing. Everywhere I looked I saw the usort() or uasort() as the suggested way to solve this problem. (Collection::sort() is just a wrapper for uasort()) but that did not satisfy me because why would I use PHP to sort when SQL should do it for me with an ORDER BY clause??? I ended up implementing it this way using an getXXXAttribute() method:

class Post extends Eloquent {    public function comments()    {        return $this->hasMany('Comment');    }    public function getCommentsAttribute()    {        $comments = $this->comments()->getQuery()->orderBy('created_at', 'desc')->get();        return $comments;    }    ...}


I had the same problem before but it was a one-to-one relationship. This post helped me. I ended up using a join. My code was like this:

$data = Posts::join('comments', 'comments.post_id', '=', 'posts.id')        ->order_by('comments.created_at')        ->get(array('comments.field1 as field1', 'posts.field2 as field2'));


Something like this could help.

$content = Posts::with(array('comments' => function($query) {               $query->order_by('created_at', 'asc');            }))            ->get();

Or if your problem is more complex:

How to sort by a field of the pivot table of a many-to-many relationship in Eloquent ORM