Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to order by using appended attribute in Laravel

I created an appends attribute in Laravel Model, from the code below.

    protected $appends = array('total'=>'');

And I set the returned value.

    public function getTotalAttribute(){
           return ProductPart::where('product_id',$this->id)->count();
    }

Then I want to order records from database by using total attribute

I tried to use Product::orderBy('total','desc')->get() but it didn't work.

Does anybody has some suggestions to this?

like image 261
Bun Suwanparsert Avatar asked Jan 10 '14 17:01

Bun Suwanparsert


1 Answers

the orderBy takes an actual database field not an appended one

try this

$products = Product::all();
$products = $products->sortBy(function($product){
    return $product->total;
});
like image 192
Ayobami Opeyemi Avatar answered Sep 21 '22 18:09

Ayobami Opeyemi