tattooedgeek
tattooedgeek

Reputation: 518

Laravel 4 total in table footer

I don't know if I'm not holding my toungue right or something, but I'm trying to get a total in the table footer. I have no doubt there is something I'm missing, here is what I tried:

$labors = Labor::where('created_at', '>=', new DateTime('today'))->get()->sum('labor');

Which works well up until here:

->sum('labor')

Then I get:

Call to undefined method Illuminate\Database\Eloquent\Collection::sum()

So I'm obviously using it incorrectly because it's in the docs here:

http://four.laravel.com/docs/queries

Some feedback would be much appreciated. :)

I think this might actually be relevant:

public function index()
{
    $labors = Labor::where('created_at', '>=', new DateTime('today'))->sum('labor');

    return View::make('labors.index', compact('labors'));
}

Upvotes: 0

Views: 1100

Answers (3)

Antonio Carlos Ribeiro
Antonio Carlos Ribeiro

Reputation: 87789

If you need to do a foreach, you will have to do 2 queries:

$total = Labor::where('created_at', '>=', new DateTime('today'))->sum('labor');

$labors = Labor::where('created_at', '>=', new DateTime('today'))->get();

This is because sum() returns an integer with the sum, not a collection.

Upvotes: 1

Adam Rivers
Adam Rivers

Reputation: 1075

You need to do 2 things:

$labors = Labor::where('created_at', '>=', new DateTime('today'))->get();

The above gets the array for use in the foreach.

$laborTotal = Labor::where('created_at', '>=', new DateTime('today'))->sum('labor');

That gets the total. So then is all you need to do is sent them both to the view and just use the total in the footer of the table:

return View::make('labors.index', compact('labors', 'laborTotal'));

View something like:

@foreach ($labors as $labor)
<tr> ... </tr>
@endforeach
<tr><td>{{ $laborTotal }}</td></tr>

Upvotes: 3

robjmills
robjmills

Reputation: 18598

Pretty sure it should be

$labors = Labor::where('created_at', '>=', new DateTime('today'))->sum('labor');

This is as per Eloquent Aggregates you were looking at the Fluent docs

You don't need to compact $labors now though as it's a string not an array

Upvotes: 1

Related Questions