skip to Main Content

I want this output

id jml total
1 1000 1000
1 100 1100
2 400 400
2 300 700

but when i try my output is

id jml total
1 1000 1000
1 100 100
2 400 400
2 300 300

I try this to take sum of column

$total = DB::table('logs')
         ->groupBy('id')
         ->sum('jml');

and this to add new input

$total += $request->jml;
$total = (string)$total;

3

Answers


  1. Try this using an laravel eloquent model

    $total = Log::sum('jml');
    

    or it might work using the laravel DB class like this

    $total = DB::table('logs')->sum('jml');
    
    Login or Signup to reply.
  2. The above answer should do all ID numbers even duplicate ID numbers.

    However you can also use this version which might be easier to understand and verify.

    <?php
    $sum = 0;
    $results = Log::get();
    
    if(!empty($results)) {
        foreach($results as $result) {
            $sum = $sum + $result->jml;
        }
    }
    
    echo $sum;
    
    Login or Signup to reply.
  3. The above code should work for all ID’s even duplicate ID numbers.
    However you can also do it this way.

    <?php
    $sum = 0;
    $results = Log::get();
    
    if(!empty($results)) {
        foreach($results as $result) {
            $sum = $sum + $result->jml;
        }
    }
    
    echo $sum;
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search