On a previous question I (we, because you guys helped me) did a mutator to add a column to the results I get from database.
Now my issue is: how can I order the results by the created attribute?
There is it:
public function getRatingAttribute()
{
return $this->reviews()
->selectRaw('AVG(reviews.rating) as aggregate')
->pluck('aggregate');
}
DB can't sort it for you as mutator data is fetched after the main sql request is already done. You need to sort the results in php using Collection methods, e.g.$my_results->sortByDesc('rating');
If you need to use a pagination then it is a big problem and you'll probably be better off using a join than mutators for this.