11 months ago

Sorting by appended attribute

Posted 11 months ago by nexxai

Ok, so let's say I have a model like this:


namespace App;

use Illuminate\Database\Eloquent\Model;
use App\Helpers\Helper;

class Feature extends Model

    protected $appends = [

    public function getTotalScoreAttribute()
        return $this->countTotalVotes();  // this method is inside the Helpers\Helper

and this controller method:

    public function index()
        $features = Feature::all();


        return view('features.index')->withFeatures($features);

Why does the total_score have to be computed twice, once during the initial get() but then again when I want to sort it by the score? When I return the collection before sorting, the total_score property/attribute is there, but it's like the ->sortByDesc() says "screw this, I'm doing it again myself". Am I doing something wrong, or is what I'm trying to do impossible?

Please sign in or create an account to participate in this conversation.