Hamza
Hamza

Reputation: 122

how to sum values in below array in laravel controller?

i have a laravel project i want add these 3 values sum in a variable and store in b how i can do that?

$benefit = Order::where('ot_id', $order->ot_id)->sum('ot_benefit');
$a_ben = Order::where('ot_id', $order->ot_id)->sum('subtotal') - sum('ot_benefit') - sum('discount');
$updateData = ['ben_earned' => $benefit , 'a_ben' => $a_ben];

this query create error on sum function

Upvotes: 0

Views: 1203

Answers (2)

JoeGalind
JoeGalind

Reputation: 3815

$order = Order::select(
    DB:raw('SUM(subtotal) AS st'), 
    DB:raw('SUM(ot_benefit) AS ot'),
    DB:raw('SUM(discount) AS dt')
)
->where('ot_id', $order->ot_id)
->first();

And then:

$total = $order->st + $order->ot - $order->discount;

Upvotes: 0

Maarten Veerman
Maarten Veerman

Reputation: 1621

The problem is in your second line. You cannot call the sum function like you do 3 times.

$benefit = Order::where('ot_id', $order->ot_id)->sum('ot_benefit'); 

$subtotal = Order::where('ot_id', $order->ot_id)->sum('subtotal'); 

$discount = Order::where('ot_id', $order->ot_id)->sum('discount'); 

$a_ben = $ot_benefit - $subtotal - $discount;

$updateData = ['ben_earned' => $benefit , 'a_ben' => $a_ben];

Upvotes: 2

Related Questions