I\'m new to laravel (switched from CI) and eloquent ORM is still a bit of a mystery at some point!
Here is my problem :
I\'d like to sort data from my db usi
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;
}
...
}