How to order by using appended attribute in Laravel

后端 未结 5 1050
南旧
南旧 2021-02-13 19:05

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

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

And I set the returne

5条回答
  •  心在旅途
    2021-02-13 19:50

    If working with attributes those are not always available instantly (e.g. for freshly created models).

    As expansion on Ayobami Opeyemi's answer you should be able to use Collection's sortBy if you force the attribute to evaluate by calling its function directly:

    $products = Product::all();
    $products = $products->sortBy(function($product){
        return $product->getTotalAttribute();
    });
    

    https://laravel.com/docs/master/collections#method-sortby

提交回复
热议问题