2
 $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?

Lejiend
  • 1,219
  • 2
  • 16
  • 24

2 Answers2

3

I am not sure about syntax but try with

User::all()->sum('spend_amount');

or

User::all()->select(DB::raw("SUM(spend_amount)")->get();
sensorario
  • 20,262
  • 30
  • 97
  • 159
  • i know laravel can do this , like i state at the question above, sum is just example , how about i want custom algorithm to be performed instead of sum? – Lejiend May 31 '17 at 05:16
  • 1
    Make another example and a more precise question. I'll try to give you another example and a more precise response. – sensorario May 31 '17 at 05:21
  • @sensorario your respond is right , **but** how about i want the custom one instead of sum? – Lejiend May 31 '17 at 05:32
  • It depends on what you need. Really. I cannot tell you all cases you have not mentioned here. Make a more precise question. – sensorario May 31 '17 at 05:36
  • ... maybe you can "send" the result to a service (I am talking about domain driven design). And write a family of collaborators and value object. You can resolve your problem with functional programming. You can send data to a rest api that resolves any custom issue. – sensorario May 31 '17 at 05:37
  • 1
    So, ... why dont you mark my answer as right if it is right? XD – sensorario May 31 '17 at 09:43
1

Laravel provides sum() by default using eloquent.

$total_spent_amount = DB::table('users')->all()->sum('spent_amount`);
Tijan Manandhar
  • 322
  • 3
  • 18
  • i know laravel can do this , like i state at the question above, sum is just example , how about i want custom algorithm to be performed instead of sum? – Lejiend May 31 '17 at 05:19
  • You may define a custom helper function in Laravel. Take a look at this https://stackoverflow.com/questions/28290332/best-practices-for-custom-helpers-on-laravel-5. So, each time you think you need to use that function or algorithm of yours, call it. – Tijan Manandhar May 31 '17 at 05:27