Reputation: 1299
$users = User:all();
//User:all() is based on the laravel eloquent model , it's just similar to 'select * from user' query
$total_spend_amount = 0;
foreach($users as $user)
{
$total_spend_amount += $user->spend_amount;
}
echo "Total spend amount :".$total_spend_amount;
//Note: In this simple example i just want to sum of all the spend_amount
Above are just a simple example , how do i do some algorithm on the resulted query without looping/foreach in php?
User::all()->sum('spend_amount'); // this is the answer below and this is correct
//but how about if i want the 'specific algorithm' to be performed on the resulted query instead of sum?
But how about if i want the 'specific algorithm' to be performed on the resulted query instead of sum?
Upvotes: 2
Views: 94
Reputation: 332
Laravel provides sum()
by default using eloquent.
$total_spent_amount = DB::table('users')->all()->sum('spent_amount`);
Upvotes: 1
Reputation: 21648
I am not sure about syntax but try with
User::all()->sum('spend_amount');
or
User::all()->select(DB::raw("SUM(spend_amount)")->get();
Upvotes: 3