KLM113's avatar

Subtract column value from sum() of another column

$month_revenue = Sale::whereMonth('payment_date', $month_label)->whereYear('payment_date', $year_label)->sum('total');

I need to subtract shipping_cost column from this query, would it be possible with eloquent?

0 likes
5 replies
frankincredible's avatar

Think this is the closest you'll get:

$month_revenue = Sale::selectRaw('SUM(total - shipping_cost) as month_revenue')
    ->whereMonth('payment_date', $month_label)
    ->whereYear('payment_date', $year_label)
    ->first()
    ->month_revenue;
1 like
frankincredible's avatar

@klm113 - give it a shot. This solution will definitely be more performant than two separate database queries.

Please or to participate in this conversation.