- You can user Eloquent Builder
sum()
function.
$sum = Sale::select(
DB::raw('commissioned_total as total - commission')
)
->sum('commissioned_total');
- Or you can user Laravel Collection
sum()
function.
$sum = Sale::all()->sum(function($sale) {
return $sale->total - $sale->commission;
});
- 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]