[Solved] I need to get sum of difference of two columns in each row [closed]


  1. You can user Eloquent Builder sum() function.
$sum = Sale::select(
           DB::raw('commissioned_total as total - commission')
       )
       ->sum('commissioned_total');
  1. Or you can user Laravel Collection sum() function.
$sum = Sale::all()->sum(function($sale) {
    return $sale->total - $sale->commission;
});
  1. You can enhance this method more,

Define this commissionedTotal() function on Sale model, and use sum function as Higher Order Message.

Sale Model

public function commissionedTotal()
{
    return $this->total - $this->commission;
}

Controller

$sum = Sale::all()->sum->commissionedTotal()

This third approach is more elegant and It’s the Laravel preferred way.

1

solved I need to get sum of difference of two columns in each row [closed]