How to order by using appended attribute in Laravel

the orderBy takes an actual database field not an appended one

try this

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

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


use sortBy for ASC

$collection->sortBy('field');

use sortByDesc for DESC

$collection->sortByDesc('field');