Lynx
Lynx

Reputation: 1482

Get total from mysql fields

I have prices set up in a simple mysql table and I would like to output the total price of the "services" they selected. I was able to achieve this using Laravel 4 however only way I knew how to do it was using a foreach loop. But that returns all the records that have a service and then adds them as each row is returned. How can I get just the last row returned in the foreachloop? Or is their a better method?

Foreach

        @foreach ($serviceSummary as $services)
        <tr><td>Total:</td><td>{{{ $zero += $services->price  }}}</td></tr>
        @endforeach 

Var Dump from table

var_dump($serviceSummary); die;

    array(2) {
  [0]=>
  object(stdClass)#211 (9) {
    ["id"]=>
    string(1) "1"
    ["userID"]=>
    string(1) "1"
    ["services"]=>
    string(1) "1"
    ["price"]=>
    string(4) "8.95"
    ["created_at"]=>
    string(19) "2013-10-08 19:55:47"
    ["updated_at"]=>
    string(19) "2013-10-08 19:55:47"
    ["service"]=>
    string(20) "Service"
    ["count"]=>
    string(1) "1"
    ["label"]=>
    string(2) "RC"
  }
  [1]=>
  object(stdClass)#212 (9) {
    ["id"]=>
    string(1) "1"
    ["userID"]=>
    string(1) "1"
    ["services"]=>
    string(1) "1"
    ["price"]=>
    string(4) "8.95"
    ["created_at"]=>
    string(19) "2013-10-08 20:38:56"
    ["updated_at"]=>
    string(19) "2013-10-08 20:38:56"
    ["service"]=>
    string(20) "Service"
    ["count"]=>
    string(1) "1"
    ["label"]=>
    string(2) "RC"
  }
}

basically what it looks like when printed is:

Total:  8.95
Total:  17.9

I obviously would like it to be just the total 17.9

Upvotes: 0

Views: 133

Answers (1)

Uze
Uze

Reputation: 173

Wouldn't Laravel's query builder function sum() do the trick?

In your controller:

$totalCost = DB::table('tableName')
               ->sum('price');

return View::make('your.view', array('totalCost' => $totalCost));

And then in your blade template:

Total: {{{ $totalCost }}}

Upvotes: 2

Related Questions